import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Checkbox } from '../ui/checkbox';
import { 
  Calendar, 
  Users, 
  Clock, 
  Plus, 
  Trash2, 
  Copy, 
  Save,
  X,
  ChevronLeft,
  ChevronRight,
  CheckCircle2,
  UserCheck,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export interface ScheduleShift {
  staffId: string;
  staffName: string;
  team: string;
  date: string;
  shift: '早班' | '中班' | '晚班' | '休息';
  workHours: string;
  task?: string;
}

export interface Schedule {
  id: string;
  name: string;
  type: 'week' | 'month';
  startDate: string;
  endDate: string;
  shifts: ScheduleShift[];
  status: '草稿' | '已发布';
  createdAt: string;
}

interface Staff {
  id: string;
  name: string;
  team: string;
}

interface ScheduleEditorProps {
  schedule: Schedule | null;
  staffList: Staff[];
  onSave: (schedule: Schedule) => void;
  onCancel: () => void;
}

// 示例员工数据（当没有真实员工数据时使用）
const SAMPLE_STAFF: Staff[] = [
  { id: 'sample-staff-1', name: '张三', team: '第一作业组' },
  { id: 'sample-staff-2', name: '李四', team: '第一作业组' },
  { id: 'sample-staff-3', name: '王五', team: '第二作业组' },
  { id: 'sample-staff-4', name: '赵六', team: '第二作业组' },
  { id: 'sample-staff-5', name: '孙七', team: '第三作业组' },
  { id: 'sample-staff-6', name: '周八', team: '第三作业组' },
  { id: 'sample-staff-7', name: '吴九', team: '第一作业组' },
  { id: 'sample-staff-8', name: '郑十', team: '第二作业组' },
];

export function ScheduleEditor({ schedule, staffList, onSave, onCancel }: ScheduleEditorProps) {
  const [name, setName] = useState('');
  const [type, setType] = useState<'week' | 'month'>('week');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [shifts, setShifts] = useState<ScheduleShift[]>([]);
  const [selectedStaff, setSelectedStaff] = useState<Set<string>>(new Set());
  const [currentWeekOffset, setCurrentWeekOffset] = useState(0);
  
  // 使用真实员工数据或示例数据
  const effectiveStaffList = staffList.length > 0 ? staffList : SAMPLE_STAFF;
  const isUsingSampleData = staffList.length === 0;

  // 初始化表单
  useEffect(() => {
    if (schedule) {
      setName(schedule.name);
      setType(schedule.type);
      setStartDate(schedule.startDate);
      setEndDate(schedule.endDate);
      setShifts(schedule.shifts);
    } else {
      const today = new Date();
      const start = today.toISOString().split('T')[0];
      const end = new Date(today);
      end.setDate(end.getDate() + 6);
      
      setName('');
      setType('week');
      setStartDate(start);
      setEndDate(end.toISOString().split('T')[0]);
      setShifts([]);
    }
  }, [schedule]);

  // 当类型改变时自动调整结束日期
  const handleTypeChange = (newType: 'week' | 'month') => {
    setType(newType);
    
    if (startDate) {
      const start = new Date(startDate);
      const end = new Date(start);
      
      if (newType === 'week') {
        end.setDate(end.getDate() + 6);
      } else {
        end.setMonth(end.getMonth() + 1);
        end.setDate(end.getDate() - 1);
      }
      
      setEndDate(end.toISOString().split('T')[0]);
    }
  };

  // 生成日期范围
  const getDateRange = (): Date[] => {
    if (!startDate || !endDate) return [];
    
    const dates: Date[] = [];
    const current = new Date(startDate);
    const end = new Date(endDate);
    
    while (current <= end) {
      dates.push(new Date(current));
      current.setDate(current.getDate() + 1);
    }
    
    return dates;
  };

  // 获取当前显示的周（用于月排班的分页显示）
  const getCurrentWeekDates = (): Date[] => {
    const allDates = getDateRange();
    if (type === 'week') return allDates;
    
    // 月排班按周分页显示
    const startIndex = currentWeekOffset * 7;
    return allDates.slice(startIndex, startIndex + 7);
  };

  const currentDates = getCurrentWeekDates();
  const allDates = getDateRange();
  const totalWeeks = Math.ceil(allDates.length / 7);

  // 添加人员到排班
  const handleAddStaff = (staffIds?: string[]) => {
    const idsToAdd = staffIds || Array.from(selectedStaff);
    if (idsToAdd.length === 0) {
      toast.error('请至少选择一名员工');
      return;
    }

    const newShifts: ScheduleShift[] = [];
    const dates = getDateRange();

    idsToAdd.forEach(staffId => {
      const staff = effectiveStaffList.find(s => s.id === staffId);
      if (!staff) return;

      dates.forEach(date => {
        const dateStr = date.toISOString().split('T')[0];
        
        // 检查是否已存在该员工在该日期的排班
        const existingShift = shifts.find(
          s => s.staffId === staffId && s.date === dateStr
        );
        
        if (!existingShift) {
          newShifts.push({
            staffId: staff.id,
            staffName: staff.name,
            team: staff.team,
            date: dateStr,
            shift: '早班',
            workHours: '08:00-16:00',
          });
        }
      });
    });

    setShifts([...shifts, ...newShifts]);
    setSelectedStaff(new Set());
    toast.success(`已添加 ${idsToAdd.length} 名员工到排班${isUsingSampleData ? '（使用示例数据）' : ''}`);
  };

  // 批量添加所有员工
  const handleAddAllStaff = () => {
    handleAddStaff(effectiveStaffList.map(s => s.id));
  };

  // 更新单个班次
  const updateShift = (staffId: string, date: string, updates: Partial<ScheduleShift>) => {
    setShifts(shifts.map(shift => {
      if (shift.staffId === staffId && shift.date === date) {
        return { ...shift, ...updates };
      }
      return shift;
    }));
  };

  // 删除员工的所有排班
  const removeStaffFromSchedule = (staffId: string) => {
    if (!confirm('确定要移除该员工的所有排班吗？')) return;
    
    setShifts(shifts.filter(s => s.staffId !== staffId));
    toast.success('已移除员工排班');
  };

  // 复制某一天的排班到其他天
  const copyDayShifts = (sourceDate: string) => {
    const sourceDateShifts = shifts.filter(s => s.date === sourceDate);
    if (sourceDateShifts.length === 0) {
      toast.error('该日期没有排班可复制');
      return;
    }

    const dates = getDateRange();
    const newShifts: ScheduleShift[] = [];

    dates.forEach(date => {
      const dateStr = date.toISOString().split('T')[0];
      if (dateStr === sourceDate) return;

      sourceDateShifts.forEach(sourceShift => {
        // 检查是否已存在
        const exists = shifts.some(s => s.staffId === sourceShift.staffId && s.date === dateStr);
        if (!exists) {
          newShifts.push({
            ...sourceShift,
            date: dateStr,
          });
        }
      });
    });

    if (newShifts.length > 0) {
      setShifts([...shifts, ...newShifts]);
      toast.success(`已复制 ${newShifts.length} 个班次`);
    } else {
      toast.info('所有日期都已有排班');
    }
  };

  // 批量设置班次类型
  const batchSetShiftType = (staffId: string, shiftType: '早班' | '中班' | '晚班' | '休息') => {
    const workHoursMap = {
      '早班': '08:00-16:00',
      '中班': '12:00-20:00',
      '晚班': '16:00-00:00',
      '休息': '-',
    };

    setShifts(shifts.map(shift => {
      if (shift.staffId === staffId) {
        return {
          ...shift,
          shift: shiftType,
          workHours: workHoursMap[shiftType],
        };
      }
      return shift;
    }));

    toast.success('已批量设置班次');
  };

  // 保存排班
  const handleSave = () => {
    if (!name.trim()) {
      toast.error('请输入排班名称');
      return;
    }

    if (!startDate || !endDate) {
      toast.error('请选择排班日期范围');
      return;
    }

    if (new Date(endDate) < new Date(startDate)) {
      toast.error('结束日期不能早于开始日期');
      return;
    }

    if (shifts.length === 0) {
      toast.error('请至少添加一个员工的排班');
      return;
    }

    const savedSchedule: Schedule = {
      id: schedule?.id || `schedule-${Date.now()}`,
      name,
      type,
      startDate,
      endDate,
      shifts,
      status: schedule?.status || '草稿',
      createdAt: schedule?.createdAt || new Date().toISOString(),
    };

    onSave(savedSchedule);
  };

  // 获取已排班的员工列表
  const scheduledStaffIds = new Set(shifts.map(s => s.staffId));
  const scheduledStaff = effectiveStaffList.filter(s => scheduledStaffIds.has(s.id));
  const unscheduledStaff = effectiveStaffList.filter(s => !scheduledStaffIds.has(s.id));

  // 获取某个员工在某一天的排班
  const getShift = (staffId: string, date: string): ScheduleShift | undefined => {
    return shifts.find(s => s.staffId === staffId && s.date === date);
  };

  // 获取班次类型的样式
  const getShiftBadgeVariant = (shift: '早班' | '中班' | '晚班' | '休息') => {
    switch (shift) {
      case '早班': return 'default';
      case '中班': return 'secondary';
      case '晚班': return 'outline';
      case '休息': return 'destructive';
    }
  };

  return (
    <div className="space-y-6">
      {/* 基本信息 */}
      <Card className="p-6">
        <h3 className="text-green-700 mb-4 flex items-center gap-2">
          <Calendar className="w-5 h-5" />
          排班基本信息
        </h3>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block mb-2">排班名称 *</label>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="例如：2024年3月第1周排班"
            />
          </div>

          <div>
            <label className="block mb-2">排班类型 *</label>
            <Select value={type} onValueChange={handleTypeChange}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="week">周排班（7天）</SelectItem>
                <SelectItem value="month">月排班（30天）</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <label className="block mb-2">开始日期 *</label>
            <Input
              type="date"
              value={startDate}
              onChange={(e) => {
                setStartDate(e.target.value);
                // 自动调整结束日期
                if (e.target.value) {
                  const start = new Date(e.target.value);
                  const end = new Date(start);
                  end.setDate(end.getDate() + (type === 'week' ? 6 : 29));
                  setEndDate(end.toISOString().split('T')[0]);
                }
              }}
            />
          </div>

          <div>
            <label className="block mb-2">结束日期 *</label>
            <Input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
            />
          </div>
        </div>

        <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-md text-sm text-blue-900">
          <p><strong>排班周期：</strong> {startDate && endDate ? `${startDate} 至 ${endDate}（共 ${allDates.length} 天）` : '请选择日期范围'}</p>
          <p className="mt-1"><strong>已排班人员：</strong> {scheduledStaffIds.size} 人，共 {shifts.length} 个班次</p>
        </div>
      </Card>

      {/* 人员选择 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-green-700 flex items-center gap-2">
            <Users className="w-5 h-5" />
            添加排班人员
          </h3>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={handleAddAllStaff}
              disabled={effectiveStaffList.length === scheduledStaffIds.size}
            >
              <UserCheck className="w-4 h-4 mr-2" />
              添加全部员工
            </Button>
            <Button
              size="sm"
              onClick={() => handleAddStaff()}
              disabled={selectedStaff.size === 0}
            >
              <Plus className="w-4 h-4 mr-2" />
              添加选中员工 ({selectedStaff.size})
            </Button>
          </div>
        </div>

        {/* 示例数据提示 */}
        {isUsingSampleData && (
          <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md text-sm text-blue-900">
            <p><strong>提示：</strong>当前使用示例员工数据进行演示</p>
            <p className="text-xs mt-1">实际使用时，请先在"系统配置 → 用户管理 → 员工管理"中添加真实员工信息</p>
          </div>
        )}

        {unscheduledStaff.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {unscheduledStaff.map(staff => (
              <div
                key={staff.id}
                className="flex items-center gap-2 p-3 border rounded-md hover:bg-gray-50 cursor-pointer"
                onClick={() => {
                  const newSelected = new Set(selectedStaff);
                  if (newSelected.has(staff.id)) {
                    newSelected.delete(staff.id);
                  } else {
                    newSelected.add(staff.id);
                  }
                  setSelectedStaff(newSelected);
                }}
              >
                <Checkbox
                  checked={selectedStaff.has(staff.id)}
                  onCheckedChange={(checked) => {
                    const newSelected = new Set(selectedStaff);
                    if (checked) {
                      newSelected.add(staff.id);
                    } else {
                      newSelected.delete(staff.id);
                    }
                    setSelectedStaff(newSelected);
                  }}
                />
                <div className="flex-1 min-w-0">
                  <p className="truncate">{staff.name}</p>
                  <p className="text-xs text-muted-foreground truncate">{staff.team}</p>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8 text-muted-foreground">
            <CheckCircle2 className="w-12 h-12 mx-auto mb-2 text-green-500" />
            <p>所有员工都已添加到排班中</p>
          </div>
        )}
      </Card>

      {/* 排班表 */}
      {scheduledStaff.length > 0 && (
        <Card className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-green-700 flex items-center gap-2">
              <Clock className="w-5 h-5" />
              排班详情
            </h3>
            
            {type === 'month' && totalWeeks > 1 && (
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentWeekOffset(Math.max(0, currentWeekOffset - 1))}
                  disabled={currentWeekOffset === 0}
                >
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <span className="text-sm">
                  第 {currentWeekOffset + 1} / {totalWeeks} 周
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentWeekOffset(Math.min(totalWeeks - 1, currentWeekOffset + 1))}
                  disabled={currentWeekOffset === totalWeeks - 1}
                >
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>
            )}
          </div>

          <div className="overflow-x-auto">
            <table className="w-full border-collapse min-w-[800px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border p-2 text-left sticky left-0 bg-gray-50 z-10 min-w-[120px]">
                    员工姓名
                  </th>
                  <th className="border p-2 text-left min-w-[100px]">班组</th>
                  <th className="border p-2 text-center min-w-[100px]">批量操作</th>
                  {currentDates.map((date) => {
                    const dateStr = date.toISOString().split('T')[0];
                    const dayOfWeek = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
                    return (
                      <th key={dateStr} className="border p-2 text-center min-w-[140px]">
                        <div className="text-xs">
                          <div>{date.getMonth() + 1}/{date.getDate()}</div>
                          <div className="text-muted-foreground">周{dayOfWeek}</div>
                        </div>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="mt-1 h-6 text-xs"
                          onClick={() => copyDayShifts(dateStr)}
                        >
                          <Copy className="w-3 h-3 mr-1" />
                          复制
                        </Button>
                      </th>
                    );
                  })}
                  <th className="border p-2 text-center min-w-[80px]">操作</th>
                </tr>
              </thead>
              <tbody>
                {scheduledStaff.map((staff) => (
                  <tr key={staff.id} className="hover:bg-gray-50">
                    <td className="border p-2 sticky left-0 bg-white z-10">
                      <div className="font-medium">{staff.name}</div>
                    </td>
                    <td className="border p-2">
                      <div className="text-sm text-muted-foreground">{staff.team}</div>
                    </td>
                    <td className="border p-2">
                      <Select
                        onValueChange={(value) => batchSetShiftType(staff.id, value as any)}
                      >
                        <SelectTrigger className="h-8 text-xs">
                          <SelectValue placeholder="批量设置" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="早班">全部早班</SelectItem>
                          <SelectItem value="中班">全部中班</SelectItem>
                          <SelectItem value="晚班">全部晚班</SelectItem>
                          <SelectItem value="休息">全部休息</SelectItem>
                        </SelectContent>
                      </Select>
                    </td>
                    {currentDates.map((date) => {
                      const dateStr = date.toISOString().split('T')[0];
                      const shift = getShift(staff.id, dateStr);
                      
                      return (
                        <td key={dateStr} className="border p-2">
                          {shift ? (
                            <div className="space-y-1">
                              <Select
                                value={shift.shift}
                                onValueChange={(value) => {
                                  const workHoursMap = {
                                    '早班': '08:00-16:00',
                                    '中班': '12:00-20:00',
                                    '晚班': '16:00-00:00',
                                    '休息': '-',
                                  };
                                  updateShift(staff.id, dateStr, {
                                    shift: value as any,
                                    workHours: workHoursMap[value as keyof typeof workHoursMap],
                                  });
                                }}
                              >
                                <SelectTrigger className="h-7 text-xs">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="早班">早班</SelectItem>
                                  <SelectItem value="中班">中班</SelectItem>
                                  <SelectItem value="晚班">晚班</SelectItem>
                                  <SelectItem value="休息">休息</SelectItem>
                                </SelectContent>
                              </Select>
                              {shift.shift !== '休息' && (
                                <Input
                                  type="text"
                                  value={shift.workHours}
                                  onChange={(e) => updateShift(staff.id, dateStr, { workHours: e.target.value })}
                                  className="h-7 text-xs"
                                  placeholder="08:00-16:00"
                                />
                              )}
                              {shift.shift !== '休息' && (
                                <Input
                                  type="text"
                                  value={shift.task || ''}
                                  onChange={(e) => updateShift(staff.id, dateStr, { task: e.target.value })}
                                  className="h-7 text-xs"
                                  placeholder="任务（可选）"
                                />
                              )}
                            </div>
                          ) : (
                            <div className="text-center text-muted-foreground text-xs">-</div>
                          )}
                        </td>
                      );
                    })}
                    <td className="border p-2 text-center">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => removeStaffFromSchedule(staff.id)}
                        className="h-8"
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="mt-4 p-3 bg-gray-50 rounded-md text-sm text-muted-foreground">
            <p><strong>操作说明：</strong></p>
            <ul className="mt-2 space-y-1 text-xs">
              <li>• 点击"复制"按钮可将某一天的排班复制到其他所有日期</li>
              <li>• 使用"批量操作"可快速设置某个员工的所有班次</li>
              <li>• 每个单元格可单独设置班次类型、工作时间和任务</li>
              <li>• 休息日不需要填写工作时间和任务</li>
            </ul>
          </div>
        </Card>
      )}

      {/* 操作按钮 */}
      <div className="flex justify-end gap-3">
        <Button variant="outline" onClick={onCancel}>
          <X className="w-4 h-4 mr-2" />
          取消
        </Button>
        <Button onClick={handleSave} className="bg-green-600 hover:bg-green-700">
          <Save className="w-4 h-4 mr-2" />
          保存排班
        </Button>
      </div>
    </div>
  );
}
