import { useState } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Textarea } from '../../ui/textarea';
import { Label } from '../../ui/label';
import { Task, TaskStatus } from '../../../types/task';
import { 
  CheckCircle2, 
  XCircle, 
  Play, 
  Pause, 
  AlertCircle,
  ArrowRight,
  Clock,
  User,
  Tractor
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface TaskStatusManagerProps {
  task: Task;
  onStatusChange: (taskId: string, newStatus: TaskStatus, note?: string) => void;
}

export function TaskStatusManager({ task, onStatusChange }: TaskStatusManagerProps) {
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [targetStatus, setTargetStatus] = useState<TaskStatus | null>(null);
  const [statusNote, setStatusNote] = useState('');

  // 获取任务状态颜色
  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case '待分配': return 'bg-yellow-100 text-yellow-700 border-yellow-300';
      case '已分配': return 'bg-purple-100 text-purple-700 border-purple-300';
      case '进行中': return 'bg-blue-100 text-blue-700 border-blue-300';
      case '已完成': return 'bg-green-100 text-green-700 border-green-300';
      case '已取消': return 'bg-gray-100 text-gray-700 border-gray-300';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: TaskStatus) => {
    switch (status) {
      case '待分配': return <Clock className="w-4 h-4" />;
      case '已分配': return <User className="w-4 h-4" />;
      case '进行中': return <Play className="w-4 h-4" />;
      case '已完成': return <CheckCircle2 className="w-4 h-4" />;
      case '已取消': return <XCircle className="w-4 h-4" />;
      default: return <AlertCircle className="w-4 h-4" />;
    }
  };

  // 获取可用的状态流转操作
  const getAvailableActions = () => {
    const actions: { status: TaskStatus; label: string; color: string; icon: any }[] = [];

    switch (task.status) {
      case '待分配':
        if (task.machineryId && task.driverId) {
          actions.push({ 
            status: '已分配', 
            label: '确认分配', 
            color: 'bg-purple-600 hover:bg-purple-700',
            icon: <User className="w-4 h-4" />
          });
        }
        actions.push({ 
          status: '已取消', 
          label: '取消任务', 
          color: 'bg-gray-600 hover:bg-gray-700',
          icon: <XCircle className="w-4 h-4" />
        });
        break;

      case '已分配':
        actions.push({ 
          status: '进行中', 
          label: '开始执行', 
          color: 'bg-blue-600 hover:bg-blue-700',
          icon: <Play className="w-4 h-4" />
        });
        actions.push({ 
          status: '已取消', 
          label: '取消任务', 
          color: 'bg-gray-600 hover:bg-gray-700',
          icon: <XCircle className="w-4 h-4" />
        });
        break;

      case '进行中':
        actions.push({ 
          status: '已完成', 
          label: '完成任务', 
          color: 'bg-green-600 hover:bg-green-700',
          icon: <CheckCircle2 className="w-4 h-4" />
        });
        actions.push({ 
          status: '已取消', 
          label: '中止任务', 
          color: 'bg-gray-600 hover:bg-gray-700',
          icon: <XCircle className="w-4 h-4" />
        });
        break;

      case '已完成':
      case '已取消':
        // 已结束的任务没有可用操作
        break;
    }

    return actions;
  };

  // 处理状态变更
  const handleStatusChange = (newStatus: TaskStatus) => {
    setTargetStatus(newStatus);
    setStatusNote('');
    setShowConfirmDialog(true);
  };

  // 确认状态变更
  const confirmStatusChange = () => {
    if (!targetStatus) return;

    // 验证必要条件
    if (targetStatus === '已分配' && (!task.machineryId || !task.driverId)) {
      toast.error('请先分配农机和驾驶员');
      return;
    }

    onStatusChange(task.id, targetStatus, statusNote);
    setShowConfirmDialog(false);
    setTargetStatus(null);
    setStatusNote('');
  };

  const actions = getAvailableActions();

  return (
    <>
      <Card className="p-4">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h4 className="mb-2">任务状态</h4>
            <Badge className={getStatusColor(task.status)}>
              <div className="flex items-center gap-2">
                {getStatusIcon(task.status)}
                <span>{task.status}</span>
              </div>
            </Badge>
          </div>
          
          {actions.length > 0 && (
            <div className="flex gap-2">
              {actions.map((action) => (
                <Button
                  key={action.status}
                  onClick={() => handleStatusChange(action.status)}
                  className={action.color}
                  size="sm"
                >
                  {action.icon}
                  <span className="ml-2">{action.label}</span>
                </Button>
              ))}
            </div>
          )}
        </div>

        {/* 任务信息摘要 */}
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div className="flex items-center gap-2">
            <Tractor className="w-4 h-4 text-muted-foreground" />
            <span className="text-muted-foreground">农机:</span>
            <span className={!task.machineryName ? 'text-orange-600' : ''}>
              {task.machineryName || '未分配'}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <User className="w-4 h-4 text-muted-foreground" />
            <span className="text-muted-foreground">驾驶员:</span>
            <span className={!task.driverName ? 'text-orange-600' : ''}>
              {task.driverName || '未分配'}
            </span>
          </div>
        </div>

        {/* 状态流转提示 */}
        {task.status === '待分配' && (!task.machineryId || !task.driverId) && (
          <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
            <div className="flex items-start gap-2">
              <AlertCircle className="w-4 h-4 text-yellow-600 mt-0.5" />
              <div className="text-sm text-yellow-800">
                <p className="mb-1">请先完成资源分配：</p>
                <ul className="list-disc list-inside space-y-1">
                  {!task.machineryId && <li>未分配农机</li>}
                  {!task.driverId && <li>未分配驾驶员</li>}
                </ul>
              </div>
            </div>
          </div>
        )}
      </Card>

      {/* 状态变更确认对话框 */}
      <Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认状态变更</DialogTitle>
            <DialogDescription>
              将任务状态从 "{task.status}" 变更为 "{targetStatus}"
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 状态流转可视化 */}
            <div className="flex items-center justify-center gap-4 p-4 bg-gray-50 rounded-lg">
              <Badge className={getStatusColor(task.status)}>
                <div className="flex items-center gap-2">
                  {getStatusIcon(task.status)}
                  <span>{task.status}</span>
                </div>
              </Badge>
              <ArrowRight className="w-6 h-6 text-muted-foreground" />
              <Badge className={targetStatus ? getStatusColor(targetStatus) : ''}>
                <div className="flex items-center gap-2">
                  {targetStatus && getStatusIcon(targetStatus)}
                  <span>{targetStatus}</span>
                </div>
              </Badge>
            </div>

            {/* 备注 */}
            <div>
              <Label htmlFor="statusNote">备注（可选）</Label>
              <Textarea
                id="statusNote"
                value={statusNote}
                onChange={(e) => setStatusNote(e.target.value)}
                placeholder="记录状态变更的原因或说明..."
                rows={3}
                className="mt-2"
              />
            </div>

            {/* 警告提示 */}
            {targetStatus === '已取消' && (
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-red-600 mt-0.5" />
                  <div className="text-sm text-red-800">
                    <p className="mb-1">取消任务后：</p>
                    <ul className="list-disc list-inside space-y-1">
                      <li>任务将无法再次启动</li>
                      <li>已分配的资源将被释放</li>
                      <li>此操作不可撤销</li>
                    </ul>
                  </div>
                </div>
              </div>
            )}

            {targetStatus === '已完成' && (
              <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
                <div className="flex items-start gap-2">
                  <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5" />
                  <div className="text-sm text-green-800">
                    <p>确认任务已按要求完成所有作业内容</p>
                  </div>
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowConfirmDialog(false)}>
              取消
            </Button>
            <Button onClick={confirmStatusChange}>
              确认变更
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
