import { useState, useMemo } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Textarea } from '../../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Task, TaskType, TaskPriority, Field } from '../../../types/task';
import { MachineryRecord } from '../../../types/machinery';
import { Driver } from '../../../types/driver';
import { AlertCircle, Calendar, MapPin, Tractor, User } from 'lucide-react';
import { useForm } from 'react-hook-form@7.55.0';

interface TaskFormProps {
  open: boolean;
  onClose: () => void;
  onSave: (task: Partial<Task>) => void;
  editingTask?: Task | null;
  machinery: MachineryRecord[];
  drivers: Driver[];
  fields: Field[];
  existingTasks: Task[]; // 新增：用于冲突检测
}

export function TaskForm({ open, onClose, onSave, editingTask, machinery, drivers, fields, existingTasks }: TaskFormProps) {
  const [selectedTaskType, setSelectedTaskType] = useState<TaskType>(editingTask?.taskType || '耕地');
  const [selectedPriority, setSelectedPriority] = useState<TaskPriority>(editingTask?.priority || 'medium');
  const [selectedField, setSelectedField] = useState<string>(editingTask?.fieldId || '');
  const [selectedMachinery, setSelectedMachinery] = useState<string>(editingTask?.machineryId || 'unassigned');
  const [selectedDriver, setSelectedDriver] = useState<string>(editingTask?.driverId || 'unassigned');
  const [showRequirements, setShowRequirements] = useState(false);

  const { register, handleSubmit, formState: { errors }, watch } = useForm({
    defaultValues: {
      name: editingTask?.name || '',
      description: editingTask?.description || '',
      startTime: editingTask?.startTime ? editingTask.startTime.slice(0, 16) : '',
      endTime: editingTask?.endTime ? editingTask.endTime.slice(0, 16) : '',
      workingDepth: editingTask?.requirements?.workingDepth || '',
      workingSpeed: editingTask?.requirements?.workingSpeed || '',
      seedingRate: editingTask?.requirements?.seedingRate || '',
      fertilizingRate: editingTask?.requirements?.fertilizingRate || '',
      quality: editingTask?.requirements?.quality || '',
      remarks: editingTask?.remarks || '',
    }
  });

  const startTime = watch('startTime');
  const endTime = watch('endTime');

  // 计算预估时长
  const calculateDuration = () => {
    if (startTime && endTime) {
      const start = new Date(startTime);
      const end = new Date(endTime);
      const hours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
      return hours > 0 ? hours.toFixed(1) : 0;
    }
    return 0;
  };

  const onSubmit = (data: any) => {
    const selectedFieldData = fields.find(f => f.id === selectedField);
    const selectedMachineryData = selectedMachinery && selectedMachinery !== 'unassigned' 
      ? machinery.find(m => m.id === selectedMachinery) 
      : null;
    const selectedDriverData = selectedDriver && selectedDriver !== 'unassigned'
      ? drivers.find(d => d.id === selectedDriver)
      : null;

    const task: Partial<Task> = {
      name: data.name,
      description: data.description,
      taskType: selectedTaskType,
      priority: selectedPriority,
      fieldId: selectedField || undefined,
      fieldName: selectedFieldData?.name,
      fieldArea: selectedFieldData?.area,
      machineryId: selectedMachinery && selectedMachinery !== 'unassigned' ? selectedMachinery : null,
      machineryName: selectedMachineryData?.name,
      driverId: selectedDriver && selectedDriver !== 'unassigned' ? selectedDriver : null,
      driverName: selectedDriverData?.name,
      startTime: data.startTime,
      endTime: data.endTime,
      estimatedDuration: parseFloat(calculateDuration() as string),
      requirements: {
        workingDepth: data.workingDepth ? parseFloat(data.workingDepth) : undefined,
        workingSpeed: data.workingSpeed ? parseFloat(data.workingSpeed) : undefined,
        seedingRate: data.seedingRate ? parseFloat(data.seedingRate) : undefined,
        fertilizingRate: data.fertilizingRate ? parseFloat(data.fertilizingRate) : undefined,
        quality: data.quality || undefined,
      },
      remarks: data.remarks,
      status: selectedMachinery && selectedDriver ? '已分配' : '待分配',
    };

    onSave(task);
  };

  const getPriorityColor = (priority: TaskPriority) => {
    switch (priority) {
      case 'urgent': return 'bg-error-muted text-error border-error';
      case 'high': return 'bg-warning-muted text-warning border-warning';
      case 'medium': return 'bg-warning-muted text-warning border-warning';
      case 'low': return 'bg-info-muted text-info border-info';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getPriorityText = (priority: TaskPriority) => {
    switch (priority) {
      case 'urgent': return '紧急';
      case 'high': return '高';
      case 'medium': return '中';
      case 'low': return '低';
      default: return priority;
    }
  };

  // 检查时间冲突
  const conflicts = useMemo(() => {
    const conflictList: string[] = [];
    const startTimeValue = watch('startTime');
    const endTimeValue = watch('endTime');
    
    if (!startTimeValue || !endTimeValue) {
      return conflictList;
    }
    
    const startDate = new Date(startTimeValue);
    const endDate = new Date(endTimeValue);
    
    // 1. 时间有效性检查
    if (startDate >= endDate) {
      conflictList.push('⚠️ 结束时间必须晚于开始时间');
    }
    
    const now = new Date();
    if (startDate < now) {
      const diff = Math.floor((now.getTime() - startDate.getTime()) / (1000 * 60));
      if (diff > 5) { // 允许5分钟误差
        conflictList.push('⚠️ 开始时间不能早于当前时间');
      }
    }
    
    // 2. 农机冲突检测
    if (selectedMachinery && selectedMachinery !== 'unassigned') {
      const machineryTasks = existingTasks.filter(task => {
        // 排除正在编辑的任务
        if (editingTask && task.id === editingTask.id) return false;
        // 只检查已分配给该农机的任务
        if (task.machineryId !== selectedMachinery) return false;
        // 排除已取消或已完成的任务
        if (task.status === '已取消' || task.status === '已完成') return false;
        
        const taskStart = new Date(task.startTime);
        const taskEnd = new Date(task.endTime);
        
        // 检查时间重叠
        return (startDate < taskEnd && endDate > taskStart);
      });
      
      if (machineryTasks.length > 0) {
        const machineryData = machinery.find(m => m.id === selectedMachinery);
        const taskNames = machineryTasks.map(t => `"${t.name}"`).join('、');
        conflictList.push(
          `🚜 农机"${machineryData?.name}"在此时段已有 ${machineryTasks.length} 个任务：${taskNames}`
        );
      }
    }
    
    // 3. 驾驶员冲突检测
    if (selectedDriver && selectedDriver !== 'unassigned') {
      const driverTasks = existingTasks.filter(task => {
        if (editingTask && task.id === editingTask.id) return false;
        if (task.driverId !== selectedDriver) return false;
        if (task.status === '已取消' || task.status === '已完成') return false;
        
        const taskStart = new Date(task.startTime);
        const taskEnd = new Date(task.endTime);
        
        return (startDate < taskEnd && endDate > taskStart);
      });
      
      if (driverTasks.length > 0) {
        const driverData = drivers.find(d => d.id === selectedDriver);
        const taskNames = driverTasks.map(t => `"${t.name}"`).join('、');
        conflictList.push(
          `👤 驾驶员"${driverData?.name}"在此时段已有 ${driverTasks.length} 个任务：${taskNames}`
        );
      }
    }
    
    // 4. 地块冲突检测
    if (selectedField) {
      const fieldTasks = existingTasks.filter(task => {
        if (editingTask && task.id === editingTask.id) return false;
        if (task.fieldId !== selectedField) return false;
        if (task.status === '已取消' || task.status === '已完成') return false;
        
        const taskStart = new Date(task.startTime);
        const taskEnd = new Date(task.endTime);
        
        return (startDate < taskEnd && endDate > taskStart);
      });
      
      if (fieldTasks.length > 0) {
        const fieldData = fields.find(f => f.id === selectedField);
        const taskNames = fieldTasks.map(t => `"${t.name}"`).join('、');
        conflictList.push(
          `🌾 地块"${fieldData?.name}"在此时段已有 ${fieldTasks.length} 个作业任务：${taskNames}`
        );
      }
    }
    
    return conflictList;
  }, [
    watch('startTime'),
    watch('endTime'),
    selectedMachinery,
    selectedDriver,
    selectedField,
    existingTasks,
    editingTask,
    machinery,
    drivers,
    fields
  ]);

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{editingTask ? '编辑任务' : '创建新任务'}</DialogTitle>
          <DialogDescription className="sr-only">
            {editingTask ? '编辑任务信息' : '创建新的任务'}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4">
              <h3 className="mb-4">基本信息</h3>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="name">任务名称 *</Label>
                    <Input
                      id="name"
                      {...register('name', { required: '请输入任务名称' })}
                      placeholder="如：1号地块耕地作业"
                    />
                    {errors.name && (
                      <p className="text-sm text-destructive mt-1">{errors.name.message}</p>
                    )}
                  </div>

                  <div>
                    <Label>任务类型 *</Label>
                    <Select value={selectedTaskType} onValueChange={(v) => setSelectedTaskType(v as TaskType)}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="耕地">耕地</SelectItem>
                        <SelectItem value="播种">播种</SelectItem>
                        <SelectItem value="施肥">施肥</SelectItem>
                        <SelectItem value="灌溉">灌溉</SelectItem>
                        <SelectItem value="喷药">喷药</SelectItem>
                        <SelectItem value="收获">收获</SelectItem>
                        <SelectItem value="运输">运输</SelectItem>
                        <SelectItem value="其他">其他</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div>
                  <Label htmlFor="description">任务描述</Label>
                  <Textarea
                    id="description"
                    {...register('description')}
                    rows={3}
                    placeholder="详细描述任务内容和要求..."
                  />
                </div>

                <div>
                  <Label>优先级</Label>
                  <div className="flex gap-2 mt-2">
                    {(['low', 'medium', 'high', 'urgent'] as TaskPriority[]).map(priority => (
                      <Badge
                        key={priority}
                        variant={selectedPriority === priority ? 'default' : 'outline'}
                        className={`cursor-pointer ${selectedPriority === priority ? getPriorityColor(priority) : ''}`}
                        onClick={() => setSelectedPriority(priority)}
                      >
                        {getPriorityText(priority)}
                      </Badge>
                    ))}
                  </div>
                </div>
              </div>
            </Card>

            {/* 地块信息 */}
            <Card className="p-4">
              <div className="flex items-center gap-2 mb-4">
                <MapPin className="w-5 h-5 text-success" />
                <h3>地块信息</h3>
              </div>
              <div className="space-y-4">
                <div>
                  <Label>选择地块</Label>
                  <Select value={selectedField} onValueChange={setSelectedField}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择作业地块" />
                    </SelectTrigger>
                    <SelectContent>
                      {fields.map(field => (
                        <SelectItem key={field.id} value={field.id}>
                          {field.name} - {field.area} 亩
                          {field.cropType && ` (${field.cropType})`}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {selectedField && (
                  <div className="p-3 bg-success-muted rounded-lg">
                    {(() => {
                      const field = fields.find(f => f.id === selectedField);
                      return field ? (
                        <div className="grid grid-cols-3 gap-3 text-sm">
                          <div>
                            <span className="text-muted-foreground">地块面积:</span>
                            <span className="ml-2">{field.area} 亩</span>
                          </div>
                          {field.location && (
                            <div>
                              <span className="text-muted-foreground">位置:</span>
                              <span className="ml-2">{field.location}</span>
                            </div>
                          )}
                          {field.cropType && (
                            <div>
                              <span className="text-muted-foreground">作物:</span>
                              <span className="ml-2">{field.cropType}</span>
                            </div>
                          )}
                        </div>
                      ) : null;
                    })()}
                  </div>
                )}
              </div>
            </Card>

            {/* 时间安排 */}
            <Card className="p-4">
              <div className="flex items-center gap-2 mb-4">
                <Calendar className="w-5 h-5 text-blue-600" />
                <h3>时间安排</h3>
              </div>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="startTime">开始时间 *</Label>
                    <Input
                      id="startTime"
                      type="datetime-local"
                      {...register('startTime', { required: '请选择开始时间' })}
                    />
                    {errors.startTime && (
                      <p className="text-sm text-destructive mt-1">{errors.startTime.message}</p>
                    )}
                  </div>

                  <div>
                    <Label htmlFor="endTime">结束时间 *</Label>
                    <Input
                      id="endTime"
                      type="datetime-local"
                      {...register('endTime', { required: '请选择结束时间' })}
                    />
                    {errors.endTime && (
                      <p className="text-sm text-destructive mt-1">{errors.endTime.message}</p>
                    )}
                  </div>
                </div>

                {startTime && endTime && (
                  <div className="p-3 bg-blue-50 rounded-lg">
                    <div className="text-sm">
                      <span className="text-muted-foreground">预估时长:</span>
                      <span className="ml-2">{calculateDuration()} 小时</span>
                    </div>
                  </div>
                )}
              </div>
            </Card>

            {/* 资源分配 */}
            <Card className="p-4">
              <h3 className="mb-4">资源分配（可稍后分配）</h3>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <Tractor className="w-4 h-4 text-muted-foreground" />
                      <Label>农机设备</Label>
                    </div>
                    <Select value={selectedMachinery} onValueChange={setSelectedMachinery}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择农机（可选）" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="unassigned">暂不分配</SelectItem>
                        {machinery.filter(m => m.status !== '维修中').map(m => (
                          <SelectItem key={m.id} value={m.id}>
                            {m.name} - {m.model}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <User className="w-4 h-4 text-muted-foreground" />
                      <Label>驾驶员</Label>
                    </div>
                    <Select value={selectedDriver} onValueChange={setSelectedDriver}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择驾驶员（可选）" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="unassigned">暂不分配</SelectItem>
                        {drivers.filter(d => d.status === 'active').map(d => (
                          <SelectItem key={d.id} value={d.id}>
                            {d.name} - {d.phone}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {(selectedMachinery === 'unassigned' || !selectedMachinery) && 
                 (selectedDriver === 'unassigned' || !selectedDriver) && (
                  <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-yellow-600 mt-0.5" />
                    <p className="text-sm text-yellow-800">
                      未分配资源的任务将进入"待分配"列表，可稍后在任务分配页面进行分配
                    </p>
                  </div>
                )}
              </div>
            </Card>

            {/* 作业要求 */}
            <Card className="p-4">
              <div className="flex items-center justify-between mb-4">
                <h3>作业要求（可选）</h3>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowRequirements(!showRequirements)}
                >
                  {showRequirements ? '收起' : '展开'}
                </Button>
              </div>

              {showRequirements && (
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    {(selectedTaskType === '耕地' || selectedTaskType === '播种') && (
                      <div>
                        <Label htmlFor="workingDepth">作业深度 (cm)</Label>
                        <Input
                          id="workingDepth"
                          type="number"
                          step="0.1"
                          {...register('workingDepth')}
                          placeholder="如：25"
                        />
                      </div>
                    )}

                    <div>
                      <Label htmlFor="workingSpeed">作业速度 (km/h)</Label>
                      <Input
                        id="workingSpeed"
                        type="number"
                        step="0.1"
                        {...register('workingSpeed')}
                        placeholder="如：6.5"
                      />
                    </div>

                    {selectedTaskType === '播种' && (
                      <div>
                        <Label htmlFor="seedingRate">播种量 (kg/亩)</Label>
                        <Input
                          id="seedingRate"
                          type="number"
                          step="0.1"
                          {...register('seedingRate')}
                          placeholder="如：3.5"
                        />
                      </div>
                    )}

                    {selectedTaskType === '施肥' && (
                      <div>
                        <Label htmlFor="fertilizingRate">施肥量 (kg/亩)</Label>
                        <Input
                          id="fertilizingRate"
                          type="number"
                          step="0.1"
                          {...register('fertilizingRate')}
                          placeholder="如：25"
                        />
                      </div>
                    )}

                    <div>
                      <Label htmlFor="quality">质量要求</Label>
                      <Select onValueChange={(value) => register('quality').onChange({ target: { value } })}>
                        <SelectTrigger>
                          <SelectValue placeholder="选择质量标准" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="standard">标准</SelectItem>
                          <SelectItem value="high">高标准</SelectItem>
                          <SelectItem value="strict">严格</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
              )}
            </Card>

            {/* 备注 */}
            <Card className="p-4">
              <h3 className="mb-4">备注</h3>
              <Textarea
                id="remarks"
                {...register('remarks')}
                rows={3}
                placeholder="其他说明或注意事项..."
              />
            </Card>

            {/* 冲突提醒 */}
            {conflicts.length > 0 && (
              <Card className="p-4 bg-red-50 border-red-200">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-5 h-5 text-red-600 mt-0.5 flex-shrink-0" />
                  <div className="flex-1">
                    <h4 className="text-red-900 mb-2">⚠️ 检测到 {conflicts.length} 个冲突</h4>
                    <ul className="space-y-2 text-sm text-red-800">
                      {conflicts.map((conflict, index) => (
                        <li key={index} className="flex items-start gap-1">
                          <span className="mt-1">•</span>
                          <span className="flex-1">{conflict}</span>
                        </li>
                      ))}
                    </ul>
                    <p className="text-xs text-red-700 mt-3 pt-3 border-t border-red-300">
                      💡 提示：您仍然可以保存此任务，但建议先解决冲突以避免资源调度问题
                    </p>
                  </div>
                </div>
              </Card>
            )}
          </div>

          <DialogFooter className="mt-6">
            <Button type="button" variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button type="submit">
              {editingTask ? '保存修改' : '创建任务'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
