import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Checkbox } from '../ui/checkbox';
import {
  Calendar as CalendarIcon,
  ChevronLeft,
  ChevronRight,
  Filter,
  Eye,
  MapPin,
  Users,
  Clock,
  Activity,
  TrendingUp,
  BarChart3,
  Grid,
  List,
  Maximize2,
  Download,
  RefreshCw,
  Zap,
  CheckCircle2,
  PlayCircle,
  Circle,
  Square,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface OperationCalendarProps {
  activePath?: string;
}

type TaskStatus = '待开始' | '进行中' | '已完成';
type TaskType = '播种' | '施肥' | '灌溉' | '除草' | '病虫害防治' | '采收';

interface CalendarTask {
  id: string;
  name: string;
  type: TaskType;
  fieldId: string;
  fieldName: string;
  crop: string; // 作物类型
  executor: string;
  startDate: string;
  endDate: string;
  status: TaskStatus;
  progress: number;
  color: string;
}

export function OperationCalendar({ activePath }: OperationCalendarProps) {
  const [activeTab, setActiveTab] = useState('view');
  const [viewMode, setViewMode] = useState<'month' | 'week' | 'day'>('month');
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [filterField, setFilterField] = useState<string>('all');
  const [filterType, setFilterType] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterCrop, setFilterCrop] = useState<string>('all');
  const [filterExecutor, setFilterExecutor] = useState<string>('all');
  const [draggedTask, setDraggedTask] = useState<CalendarTask | null>(null);
  const [showTaskDialog, setShowTaskDialog] = useState(false);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/view')) {
        setActiveTab('view');
      } else if (activePath.includes('/gantt')) {
        setActiveTab('gantt');
      } else if (activePath.includes('/progress')) {
        setActiveTab('progress');
      }
    }
  }, [activePath]);

  // 模拟任务数据
  const [tasks, setTasks] = useState<CalendarTask[]>([
    // 已完成的任务（10月上旬）
    {
      id: 'task-1',
      name: '东区1号地小麦播种',
      type: '播种',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '小麦',
      executor: '张三',
      startDate: '2025-10-01',
      endDate: '2025-10-03',
      status: '已完成',
      progress: 100,
      color: '#22c55e',
    },
    {
      id: 'task-2',
      name: '西区2号地油菜施底肥',
      type: '施肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '油菜',
      executor: '李四',
      startDate: '2025-10-02',
      endDate: '2025-10-03',
      status: '已完成',
      progress: 100,
      color: '#eab308',
    },
    {
      id: 'task-3',
      name: '南区3号地玉米采收',
      type: '采收',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '玉米',
      executor: '陈七',
      startDate: '2025-10-04',
      endDate: '2025-10-06',
      status: '已完成',
      progress: 100,
      color: '#f97316',
    },
    {
      id: 'task-4',
      name: '北区4号地水稻采收',
      type: '采收',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '水稻',
      executor: '赵六',
      startDate: '2025-10-05',
      endDate: '2025-10-07',
      status: '已完成',
      progress: 100,
      color: '#f97316',
    },
    {
      id: 'task-5',
      name: '东区1号地小麦灌溉',
      type: '灌溉',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '小麦',
      executor: '张三',
      startDate: '2025-10-08',
      endDate: '2025-10-08',
      status: '已完成',
      progress: 100,
      color: '#3b82f6',
    },
    {
      id: 'task-6',
      name: '西区2号地油菜播种',
      type: '播种',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '油菜',
      executor: '李四',
      startDate: '2025-10-07',
      endDate: '2025-10-09',
      status: '已完成',
      progress: 100,
      color: '#22c55e',
    },
    {
      id: 'task-7',
      name: '南区3号地土地翻耕',
      type: '除草',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '小麦',
      executor: '王五',
      startDate: '2025-10-10',
      endDate: '2025-10-11',
      status: '已完成',
      progress: 100,
      color: '#a855f7',
    },
    {
      id: 'task-8',
      name: '北区4号地土壤改良',
      type: '施肥',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '小麦',
      executor: '赵六',
      startDate: '2025-10-12',
      endDate: '2025-10-13',
      status: '已完成',
      progress: 100,
      color: '#eab308',
    },
    
    // 进行中的任务（10月中旬）
    {
      id: 'task-9',
      name: '东区1号地小麦除草',
      type: '除草',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '小麦',
      executor: '张三',
      startDate: '2025-10-17',
      endDate: '2025-10-19',
      status: '进行中',
      progress: 65,
      color: '#a855f7',
    },
    {
      id: 'task-10',
      name: '西区2号地油菜灌溉',
      type: '灌溉',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '油菜',
      executor: '李四',
      startDate: '2025-10-18',
      endDate: '2025-10-18',
      status: '进行中',
      progress: 80,
      color: '#3b82f6',
    },
    {
      id: 'task-11',
      name: '南区3号地小麦播种',
      type: '播种',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '小麦',
      executor: '陈七',
      startDate: '2025-10-19',
      endDate: '2025-10-21',
      status: '进行中',
      progress: 45,
      color: '#22c55e',
    },
    {
      id: 'task-12',
      name: '北区4号地小麦播种',
      type: '播种',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '小麦',
      executor: '王五',
      startDate: '2025-10-20',
      endDate: '2025-10-22',
      status: '进行中',
      progress: 30,
      color: '#22c55e',
    },
    
    // 待开始的任务（10月下旬）
    {
      id: 'task-13',
      name: '东区1号地小麦追肥',
      type: '施肥',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '小麦',
      executor: '张三',
      startDate: '2025-10-23',
      endDate: '2025-10-24',
      status: '待开始',
      progress: 0,
      color: '#eab308',
    },
    {
      id: 'task-14',
      name: '西区2号地油菜除草',
      type: '除草',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '油菜',
      executor: '李四',
      startDate: '2025-10-24',
      endDate: '2025-10-25',
      status: '待开始',
      progress: 0,
      color: '#a855f7',
    },
    {
      id: 'task-15',
      name: '南区3号地小麦灌溉',
      type: '灌溉',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '小麦',
      executor: '陈七',
      startDate: '2025-10-25',
      endDate: '2025-10-25',
      status: '待开始',
      progress: 0,
      color: '#3b82f6',
    },
    {
      id: 'task-16',
      name: '北区4号地小麦灌溉',
      type: '灌溉',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '小麦',
      executor: '赵六',
      startDate: '2025-10-26',
      endDate: '2025-10-26',
      status: '待开始',
      progress: 0,
      color: '#3b82f6',
    },
    {
      id: 'task-17',
      name: '东区1号地病虫害防治',
      type: '病虫害防治',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '小麦',
      executor: '张三',
      startDate: '2025-10-27',
      endDate: '2025-10-28',
      status: '待开始',
      progress: 0,
      color: '#ef4444',
    },
    {
      id: 'task-18',
      name: '西区2号地油菜施肥',
      type: '施肥',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '油菜',
      executor: '李四',
      startDate: '2025-10-28',
      endDate: '2025-10-29',
      status: '待开始',
      progress: 0,
      color: '#eab308',
    },
    {
      id: 'task-19',
      name: '南区3号地病虫害防治',
      type: '病虫害防治',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '小麦',
      executor: '王五',
      startDate: '2025-10-29',
      endDate: '2025-10-30',
      status: '待开始',
      progress: 0,
      color: '#ef4444',
    },
    {
      id: 'task-20',
      name: '北区4号地除草',
      type: '除草',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '小麦',
      executor: '赵六',
      startDate: '2025-10-30',
      endDate: '2025-10-31',
      status: '待开始',
      progress: 0,
      color: '#a855f7',
    },
    
    // 11月初的任务
    {
      id: 'task-21',
      name: '东区1号地小麦追肥',
      type: '施肥',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      crop: '小麦',
      executor: '张三',
      startDate: '2025-11-01',
      endDate: '2025-11-02',
      status: '待开始',
      progress: 0,
      color: '#eab308',
    },
    {
      id: 'task-22',
      name: '西区2号地油菜病虫害防治',
      type: '病虫害防治',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      crop: '油菜',
      executor: '李四',
      startDate: '2025-11-03',
      endDate: '2025-11-04',
      status: '待开始',
      progress: 0,
      color: '#ef4444',
    },
    {
      id: 'task-23',
      name: '南区3号地小麦施肥',
      type: '施肥',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      crop: '小麦',
      executor: '陈七',
      startDate: '2025-11-05',
      endDate: '2025-11-06',
      status: '待开始',
      progress: 0,
      color: '#eab308',
    },
    {
      id: 'task-24',
      name: '北区4号地小麦施肥',
      type: '施肥',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      crop: '小麦',
      executor: '王五',
      startDate: '2025-11-07',
      endDate: '2025-11-08',
      status: '待开始',
      progress: 0,
      color: '#eab308',
    },
  ]);

  const mockFields = [
    { id: 'field-1', name: '东区1号地', area: 50.5, crop: '小麦' },
    { id: 'field-2', name: '西区2号地', area: 45.2, crop: '油菜' },
    { id: 'field-3', name: '南区3号地', area: 60.3, crop: '小麦' },
    { id: 'field-4', name: '北区4号地', area: 44.0, crop: '小麦' },
  ];

  // 获取所有作物类型
  const allCrops = Array.from(new Set(tasks.map(t => t.crop)));
  
  // 获取所有执行人
  const allExecutors = Array.from(new Set(tasks.map(t => t.executor)));

  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case '待开始': return 'bg-info';
      case '进行中': return 'bg-success';
      case '已完成': return 'bg-muted';
      default: return 'bg-muted';
    }
  };

  const getStatusBadgeColor = (status: TaskStatus) => {
    switch (status) {
      case '待开始': return 'bg-info-muted text-info-muted-foreground';
      case '进行中': return 'bg-success-muted text-success-muted-foreground';
      case '已完成': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusIcon = (status: TaskStatus) => {
    switch (status) {
      case '待开始': return <Circle className="w-3 h-3" />;
      case '进行中': return <PlayCircle className="w-3 h-3" />;
      case '已完成': return <CheckCircle2 className="w-3 h-3" />;
      default: return <Circle className="w-3 h-3" />;
    }
  };

  const getTypeColor = (type: TaskType) => {
    switch (type) {
      case '播种': return '#22c55e';
      case '施肥': return '#eab308';
      case '灌溉': return '#3b82f6';
      case '除草': return '#a855f7';
      case '病虫害防治': return '#ef4444';
      case '采收': return '#f97316';
      default: return '#6b7280';
    }
  };

  // 生成日历数据
  const generateCalendarDays = () => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - firstDay.getDay());

    const days = [];
    const current = new Date(startDate);

    for (let i = 0; i < 42; i++) {
      days.push(new Date(current));
      current.setDate(current.getDate() + 1);
    }

    return days;
  };

  // 获取指定日期的任务
  const getTasksForDate = (date: Date) => {
    const dateStr = date.toISOString().split('T')[0];
    return filteredTasks.filter(task => {
      const taskStart = new Date(task.startDate);
      const taskEnd = new Date(task.endDate);
      const checkDate = new Date(dateStr);
      return checkDate >= taskStart && checkDate <= taskEnd;
    });
  };

  // 导航到上一个月
  const previousMonth = () => {
    const newDate = new Date(currentDate);
    newDate.setMonth(newDate.getMonth() - 1);
    setCurrentDate(newDate);
  };

  // 导航到下一个月
  const nextMonth = () => {
    const newDate = new Date(currentDate);
    newDate.setMonth(newDate.getMonth() + 1);
    setCurrentDate(newDate);
  };

  // 导航到今天
  const goToToday = () => {
    setCurrentDate(new Date());
  };

  // 拖拽开始
  const handleDragStart = (task: CalendarTask, e: React.DragEvent) => {
    setDraggedTask(task);
    e.dataTransfer.effectAllowed = 'move';
  };

  // 拖拽结束
  const handleDragEnd = () => {
    setDraggedTask(null);
  };

  // 放置到新日期
  const handleDrop = (date: Date, e: React.DragEvent) => {
    e.preventDefault();
    if (!draggedTask) return;

    const dateStr = date.toISOString().split('T')[0];
    const oldStartDate = new Date(draggedTask.startDate);
    const oldEndDate = new Date(draggedTask.endDate);
    const duration = Math.ceil((oldEndDate.getTime() - oldStartDate.getTime()) / (1000 * 60 * 60 * 24));

    const newEndDate = new Date(date);
    newEndDate.setDate(newEndDate.getDate() + duration);

    setTasks(tasks.map(t =>
      t.id === draggedTask.id
        ? {
            ...t,
            startDate: dateStr,
            endDate: newEndDate.toISOString().split('T')[0],
          }
        : t
    ));

    toast.success(`任务已调整至 ${dateStr}`);
    setDraggedTask(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const filteredTasks = tasks.filter(t => {
    if (filterField !== 'all' && t.fieldId !== filterField) return false;
    if (filterType !== 'all' && t.type !== filterType) return false;
    if (filterStatus !== 'all' && t.status !== filterStatus) return false;
    if (filterCrop !== 'all' && t.crop !== filterCrop) return false;
    if (filterExecutor !== 'all' && t.executor !== filterExecutor) return false;
    return true;
  });

  const calendarDays = generateCalendarDays();
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

  // 统计数据
  const totalTasks = filteredTasks.length;
  const pendingTasks = filteredTasks.filter(t => t.status === '待开始').length;
  const inProgressTasks = filteredTasks.filter(t => t.status === '进行中').length;
  const completedTasks = filteredTasks.filter(t => t.status === '已完成').length;

  // 甘特图数据处理
  const ganttStartDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
  const ganttEndDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
  const ganttDays = Math.ceil((ganttEndDate.getTime() - ganttStartDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;

  const calculateGanttPosition = (startDate: string, endDate: string) => {
    const start = new Date(startDate);
    const end = new Date(endDate);
    const daysSinceStart = Math.floor((start.getTime() - ganttStartDate.getTime()) / (1000 * 60 * 60 * 24));
    const duration = Math.floor((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
    
    const left = (daysSinceStart / ganttDays) * 100;
    const width = (duration / ganttDays) * 100;
    
    return { left: `${left}%`, width: `${width}%` };
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">农事日历</h2>
          <p className="text-muted-foreground">
            可视化农事活动日历、甘特图与进度监控
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={goToToday}>
            <CalendarIcon className="w-4 h-4 mr-2" />
            今天
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出
          </Button>
        </div>
      </div>

      {/* 统计概览 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">总任务数</p>
              <p className="mt-2 text-3xl text-foreground">{totalTasks}</p>
            </div>
            <Activity className="w-12 h-12 text-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">待开始</p>
              <p className="mt-2 text-3xl text-blue-600">{pendingTasks}</p>
            </div>
            <Circle className="w-12 h-12 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">进行中</p>
              <p className="mt-2 text-3xl text-green-600">{inProgressTasks}</p>
            </div>
            <PlayCircle className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">已完成</p>
              <p className="mt-2 text-3xl text-gray-600">{completedTasks}</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-gray-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 筛选器 */}
      <Card className="p-4">
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-muted-foreground flex-shrink-0" />
            <span className="text-sm text-muted-foreground">多维筛选：</span>
          </div>
          
          {/* 第一行筛选 */}
          <div className="flex items-center gap-3 flex-wrap">
            <Select value={filterField} onValueChange={setFilterField}>
              <SelectTrigger className="w-44">
                <SelectValue placeholder="选择地块" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部地块</SelectItem>
                {mockFields.map(field => (
                  <SelectItem key={field.id} value={field.id}>
                    {field.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={filterCrop} onValueChange={setFilterCrop}>
              <SelectTrigger className="w-44">
                <SelectValue placeholder="选择作物" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部作物</SelectItem>
                {allCrops.map(crop => (
                  <SelectItem key={crop} value={crop}>
                    {crop}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={filterExecutor} onValueChange={setFilterExecutor}>
              <SelectTrigger className="w-44">
                <SelectValue placeholder="选择负责人" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部负责人</SelectItem>
                {allExecutors.map(executor => (
                  <SelectItem key={executor} value={executor}>
                    {executor}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={filterType} onValueChange={setFilterType}>
              <SelectTrigger className="w-44">
                <SelectValue placeholder="农事类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="播种">播种</SelectItem>
                <SelectItem value="施肥">施肥</SelectItem>
                <SelectItem value="灌溉">灌溉</SelectItem>
                <SelectItem value="除草">除草</SelectItem>
                <SelectItem value="病虫害防治">病虫害防治</SelectItem>
                <SelectItem value="采收">采收</SelectItem>
              </SelectContent>
            </Select>

            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-44">
                <SelectValue placeholder="任务状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="待开始">待开始</SelectItem>
                <SelectItem value="进行中">进行中</SelectItem>
                <SelectItem value="已完成">已完成</SelectItem>
              </SelectContent>
            </Select>

            <Button 
              variant="outline" 
              size="sm"
              onClick={() => {
                setFilterField('all');
                setFilterCrop('all');
                setFilterExecutor('all');
                setFilterType('all');
                setFilterStatus('all');
                toast.success('已重置所有筛选条件');
              }}
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              重置筛选
            </Button>
          </div>

          {/* 筛选结果提示 */}
          {(filterField !== 'all' || filterCrop !== 'all' || filterExecutor !== 'all' || filterType !== 'all' || filterStatus !== 'all') && (
            <div className="flex items-center gap-2 text-sm">
              <Badge variant="outline">
                当前筛选: {filteredTasks.length} 个任务
              </Badge>
              {filterField !== 'all' && (
                <Badge variant="outline">
                  地块: {mockFields.find(f => f.id === filterField)?.name}
                </Badge>
              )}
              {filterCrop !== 'all' && (
                <Badge variant="outline">作物: {filterCrop}</Badge>
              )}
              {filterExecutor !== 'all' && (
                <Badge variant="outline">负责人: {filterExecutor}</Badge>
              )}
              {filterType !== 'all' && (
                <Badge variant="outline">类型: {filterType}</Badge>
              )}
              {filterStatus !== 'all' && (
                <Badge variant="outline">状态: {filterStatus}</Badge>
              )}
            </div>
          )}
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="view">可视化视图</TabsTrigger>
          <TabsTrigger value="gantt">甘特图</TabsTrigger>
          <TabsTrigger value="progress">进度状态可视化</TabsTrigger>
        </TabsList>

        {/* 可视化视图 - 日历 */}
        <TabsContent value="view" className="space-y-4">
          {/* 日历头部 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-4">
                <Button variant="outline" size="sm" onClick={previousMonth}>
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <h3 className="min-w-[150px] text-center">
                  {currentDate.getFullYear()}年 {monthNames[currentDate.getMonth()]}
                </h3>
                <Button variant="outline" size="sm" onClick={nextMonth}>
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>

              <div className="flex gap-2">
                <Button
                  size="sm"
                  variant={viewMode === 'month' ? 'default' : 'outline'}
                  onClick={() => setViewMode('month')}
                >
                  月
                </Button>
                <Button
                  size="sm"
                  variant={viewMode === 'week' ? 'default' : 'outline'}
                  onClick={() => setViewMode('week')}
                >
                  周
                </Button>
                <Button
                  size="sm"
                  variant={viewMode === 'day' ? 'default' : 'outline'}
                  onClick={() => setViewMode('day')}
                >
                  日
                </Button>
              </div>
            </div>

            {/* 日历网格 */}
            <div className="border rounded-lg overflow-hidden">
              {/* 星期标题 */}
              <div className="grid grid-cols-7 bg-muted">
                {weekDays.map(day => (
                  <div key={day} className="p-3 text-center text-sm font-medium border-r last:border-r-0">
                    星期{day}
                  </div>
                ))}
              </div>

              {/* 日期网格 */}
              <div className="grid grid-cols-7">
                {calendarDays.map((day, index) => {
                  const isCurrentMonth = day.getMonth() === currentDate.getMonth();
                  const isToday =
                    day.getDate() === new Date().getDate() &&
                    day.getMonth() === new Date().getMonth() &&
                    day.getFullYear() === new Date().getFullYear();
                  const dayTasks = getTasksForDate(day);

                  return (
                    <div
                      key={index}
                      className={`min-h-[120px] p-2 border-r border-b last:border-r-0 ${
                        !isCurrentMonth ? 'bg-muted' : 'bg-card'
                      } ${isToday ? 'ring-2 ring-green-500' : ''}`}
                      onDrop={(e) => handleDrop(day, e)}
                      onDragOver={handleDragOver}
                    >
                      <div className={`text-sm mb-2 ${isToday ? 'text-green-600 font-bold' : ''}`}>
                        {day.getDate()}
                      </div>
                      <div className="space-y-1">
                        {dayTasks.slice(0, 3).map(task => (
                          <div
                            key={task.id}
                            draggable
                            onDragStart={(e) => handleDragStart(task, e)}
                            onDragEnd={handleDragEnd}
                            className="p-1 rounded text-xs cursor-move hover:shadow-md transition-shadow"
                            style={{ backgroundColor: task.color, color: 'white' }}
                          >
                            <div className="flex items-center gap-1">
                              {getStatusIcon(task.status)}
                              <span className="truncate">{task.name}</span>
                            </div>
                          </div>
                        ))}
                        {dayTasks.length > 3 && (
                          <div className="text-xs text-muted-foreground">
                            +{dayTasks.length - 3} 更多
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </Card>

          {/* 说明 */}
          <Card className="p-4">
            <div className="flex items-start gap-2">
              <Zap className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm">
                <p className="mb-2">可视化日历功能（当前展示 {filteredTasks.length} 个任务）：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>拖拽调整</strong>: 直接拖拽任务卡片到新日期，快速调整任务时间</li>
                  <li>• <strong>颜色区分</strong>: 🟢播种、🟡施肥、🔵灌溉、🟣除草、🔴病虫害防治、🟠采收</li>
                  <li>• <strong>状态图标</strong>: ⭕待开始、▶️进行中、✅已完成</li>
                  <li>• <strong>多维筛选</strong>: 按作物、地块、负责人、农事类型、状态等5个维度筛选显示</li>
                  <li>• <strong>丰富数据</strong>: 系统已加载10-11月的24个农事任务，展示秋收冬种完整周期</li>
                  <li>• <strong>快速定位</strong>: 点击"今天"按钮快速回到当前日期，使用左右箭头切换月份</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 甘特图 */}
        <TabsContent value="gantt" className="space-y-4">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-4">
                <Button variant="outline" size="sm" onClick={previousMonth}>
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <h3 className="min-w-[150px] text-center">
                  {currentDate.getFullYear()}年 {monthNames[currentDate.getMonth()]}
                </h3>
                <Button variant="outline" size="sm" onClick={nextMonth}>
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>

              <div className="flex gap-2">
                <Badge className="bg-green-100 text-green-800">
                  <Square className="w-3 h-3 mr-1 fill-current" />
                  播种
                </Badge>
                <Badge className="bg-yellow-100 text-yellow-800">
                  <Square className="w-3 h-3 mr-1 fill-current" />
                  施肥
                </Badge>
                <Badge className="bg-blue-100 text-blue-800">
                  <Square className="w-3 h-3 mr-1 fill-current" />
                  灌溉
                </Badge>
                <Badge className="bg-purple-100 text-purple-800">
                  <Square className="w-3 h-3 mr-1 fill-current" />
                  除草
                </Badge>
                <Badge className="bg-red-100 text-red-800">
                  <Square className="w-3 h-3 mr-1 fill-current" />
                  病虫害防治
                </Badge>
                <Badge className="bg-orange-100 text-orange-800">
                  <Square className="w-3 h-3 mr-1 fill-current" />
                  采收
                </Badge>
              </div>
            </div>

            {/* 甘特图时间轴 */}
            <div className="mb-4">
              <div className="grid" style={{ gridTemplateColumns: '200px 1fr' }}>
                <div className="p-2 font-medium border-b">任务</div>
                <div className="border-b">
                  <div className="grid" style={{ gridTemplateColumns: `repeat(${ganttDays}, 1fr)` }}>
                    {Array.from({ length: ganttDays }, (_, i) => (
                      <div key={i} className="p-2 text-xs text-center border-r last:border-r-0">
                        {i + 1}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* 甘特图任务条 */}
            <div className="space-y-2">
              {filteredTasks.map(task => {
                const position = calculateGanttPosition(task.startDate, task.endDate);
                return (
                  <div key={task.id} className="grid" style={{ gridTemplateColumns: '200px 1fr' }}>
                    <div className="p-3 border-b border-r flex items-center gap-2">
                      <Badge className={getStatusBadgeColor(task.status)} variant="outline">
                        {getStatusIcon(task.status)}
                      </Badge>
                      <div>
                        <p className="text-sm font-medium">{task.name}</p>
                        <p className="text-xs text-muted-foreground">{task.fieldName}</p>
                      </div>
                    </div>
                    <div className="p-3 border-b relative">
                      <div
                        className="absolute h-8 rounded flex items-center px-2 text-xs text-white cursor-pointer hover:opacity-80 transition-opacity"
                        style={{
                          backgroundColor: task.color,
                          left: position.left,
                          width: position.width,
                          top: '50%',
                          transform: 'translateY(-50%)',
                        }}
                        title={`${task.startDate} ~ ${task.endDate}`}
                      >
                        <span className="truncate">{task.progress}%</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>

          {/* 甘特图说明 */}
          <Card className="p-4">
            <div className="flex items-start gap-2">
              <BarChart3 className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm">
                <p className="mb-2">甘特图功能（当前展示 {filteredTasks.length} 个任务的时间轴）：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>时间轴展示</strong>: 横向展示所有农事活动的时间安排和持续周期，一眼看清整月安排</li>
                  <li>• <strong>进度可视化</strong>: 任务条上显示实时进度百分比，长度表示持续时间</li>
                  <li>• <strong>任务关系</strong>: 清晰展示不同地块、不同任务之间的时间关系和先后顺序</li>
                  <li>• <strong>资源冲突检测</strong>: 快速识别同一时间段的多个任务，避免人力和机械资源冲突</li>
                  <li>• <strong>丰富示例</strong>: 当前月份包含从播种、施肥、灌溉到病虫害防治、除草、采收的完整农事周期</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 进度状态可视化 */}
        <TabsContent value="progress" className="space-y-4">
          {/* 按地块分组展示 */}
          <div className="space-y-4">
            {mockFields.map(field => {
              const fieldTasks = filteredTasks.filter(t => t.fieldId === field.id);
              if (fieldTasks.length === 0 && filterField !== 'all') return null;

              const fieldPendingTasks = fieldTasks.filter(t => t.status === '待开始').length;
              const fieldInProgressTasks = fieldTasks.filter(t => t.status === '进行中').length;
              const fieldCompletedTasks = fieldTasks.filter(t => t.status === '已完成').length;

              return (
                <Card key={field.id} className="p-6">
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <div className="p-3 bg-green-50 rounded-lg">
                        <MapPin className="w-6 h-6 text-green-600" />
                      </div>
                      <div>
                        <h3>{field.name}</h3>
                        <p className="text-sm text-muted-foreground">
                          作物: {field.crop} | 面积: {field.area} 亩 | 任务数: {fieldTasks.length}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Badge className="bg-blue-100 text-blue-800">
                        待开始: {fieldPendingTasks}
                      </Badge>
                      <Badge className="bg-green-100 text-green-800">
                        进行中: {fieldInProgressTasks}
                      </Badge>
                      <Badge className="bg-gray-100 text-gray-800">
                        已完成: {fieldCompletedTasks}
                      </Badge>
                    </div>
                  </div>

                  {/* 进度条 */}
                  <div className="mb-4">
                    <div className="flex items-center justify-between text-sm mb-2">
                      <span className="text-muted-foreground">整体进度</span>
                      <span className="font-medium">
                        {fieldTasks.length > 0
                          ? Math.round((fieldCompletedTasks / fieldTasks.length) * 100)
                          : 0}%
                      </span>
                    </div>
                    <div className="h-3 bg-muted rounded-full overflow-hidden flex">
                      <div
                        className="bg-blue-500 transition-all"
                        style={{
                          width: `${fieldTasks.length > 0 ? (fieldPendingTasks / fieldTasks.length) * 100 : 0}%`,
                        }}
                        title={`待开始: ${fieldPendingTasks}`}
                      />
                      <div
                        className="bg-green-500 transition-all"
                        style={{
                          width: `${fieldTasks.length > 0 ? (fieldInProgressTasks / fieldTasks.length) * 100 : 0}%`,
                        }}
                        title={`进行中: ${fieldInProgressTasks}`}
                      />
                      <div
                        className="bg-gray-400 transition-all"
                        style={{
                          width: `${fieldTasks.length > 0 ? (fieldCompletedTasks / fieldTasks.length) * 100 : 0}%`,
                        }}
                        title={`已完成: ${fieldCompletedTasks}`}
                      />
                    </div>
                  </div>

                  {/* 任务列表 */}
                  <div className="grid grid-cols-3 gap-4">
                    {fieldTasks.map(task => (
                      <Card key={task.id} className="p-4 border-l-4" style={{ borderLeftColor: task.color }}>
                        <div className="flex items-start justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <Badge className={getStatusBadgeColor(task.status)} variant="outline">
                              {getStatusIcon(task.status)}
                              <span className="ml-1">{task.status}</span>
                            </Badge>
                          </div>
                        </div>
                        <h4 className="mb-2">{task.type} - {task.crop}</h4>
                        <div className="space-y-2 text-sm">
                          <div className="flex items-center gap-2 text-muted-foreground">
                            <Users className="w-3 h-3" />
                            负责人: {task.executor}
                          </div>
                          <div className="flex items-center gap-2 text-muted-foreground">
                            <Clock className="w-3 h-3" />
                            {task.startDate} ~ {task.endDate}
                          </div>
                        </div>
                        <div className="mt-3">
                          <div className="flex items-center justify-between text-xs mb-1">
                            <span className="text-muted-foreground">完成度</span>
                            <span className="font-medium">{task.progress}%</span>
                          </div>
                          <div className="h-2 bg-muted rounded-full overflow-hidden">
                            <div
                              className="h-full transition-all"
                              style={{
                                width: `${task.progress}%`,
                                backgroundColor: task.color,
                              }}
                            />
                          </div>
                        </div>
                      </Card>
                    ))}
                  </div>

                  {fieldTasks.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      该地块暂无农事任务
                    </div>
                  )}
                </Card>
              );
            })}
          </div>

          {/* 进度说明 */}
          <Card className="p-4">
            <div className="flex items-start gap-2">
              <TrendingUp className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm">
                <p className="mb-2">进度状态可视化：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>色块展示</strong>: 🔵 蓝色-待开始、🟢 绿色-进行中、⚫ 灰色-已完成</li>
                  <li>• <strong>地块分组</strong>: 按地块分组展示，清晰掌握每块地的生产节奏</li>
                  <li>• <strong>作物信息</strong>: 显示每个地块的种植作物和面积信息</li>
                  <li>• <strong>整体进度</strong>: 每个地块显示整体完成度进度条</li>
                  <li>• <strong>任务卡片</strong>: 每个任务显示作物类型、状态、负责人、时间、进度等关键信息</li>
                  <li>• <strong>快速识别</strong>: 管理层可快速掌握全局生产进度和瓶颈</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 任务详情对话框 */}
      <Dialog open={showTaskDialog} onOpenChange={setShowTaskDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>任务详情</DialogTitle>
            <DialogDescription>
              查看和编辑农事任务的详细信息
            </DialogDescription>
          </DialogHeader>
          {/* 任务详情内容 */}
        </DialogContent>
      </Dialog>
    </div>
  );
}
