import React, { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
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 { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { AlertCircle, CheckCircle, Clock, Eye, MessageSquare, Filter, Search } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { DriverTask, TaskIssue } from '../../../types/driver';

export function IssueManagement() {
  const [tasks, setTasks] = useState<DriverTask[]>([]);
  const [allIssues, setAllIssues] = useState<(TaskIssue & { taskInfo: DriverTask })[]>([]);
  const [filteredIssues, setFilteredIssues] = useState<(TaskIssue & { taskInfo: DriverTask })[]>([]);
  const [selectedIssue, setSelectedIssue] = useState<(TaskIssue & { taskInfo: DriverTask }) | null>(null);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showHandleDialog, setShowHandleDialog] = useState(false);
  
  // 筛选条件
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterType, setFilterType] = useState<string>('all');
  const [searchKeyword, setSearchKeyword] = useState('');

  // 处理信息
  const [handleNote, setHandleNote] = useState('');
  const [handleSolution, setHandleSolution] = useState('');

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    applyFilters();
  }, [allIssues, filterStatus, filterType, searchKeyword]);

  const loadData = () => {
    const tasksData = localStorage.getItem('smart_agriculture_driver_tasks');
    if (tasksData) {
      const parsedTasks: DriverTask[] = JSON.parse(tasksData);
      setTasks(parsedTasks);

      // 提取所有问题，并附加任务信息
      const issues: (TaskIssue & { taskInfo: DriverTask })[] = [];
      parsedTasks.forEach(task => {
        task.issues.forEach(issue => {
          issues.push({
            ...issue,
            taskInfo: task,
          });
        });
      });

      // 按上报时间倒序排列
      issues.sort((a, b) => new Date(b.reportedAt).getTime() - new Date(a.reportedAt).getTime());
      setAllIssues(issues);
    }
  };

  const applyFilters = () => {
    let filtered = [...allIssues];

    // 状态筛选
    if (filterStatus !== 'all') {
      filtered = filtered.filter(issue => issue.status === filterStatus);
    }

    // 类型筛选
    if (filterType !== 'all') {
      filtered = filtered.filter(issue => issue.type === filterType);
    }

    // 关键词搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(issue =>
        issue.description?.toLowerCase().includes(keyword) ||
        issue.taskInfo.taskNumber.toLowerCase().includes(keyword) ||
        issue.taskInfo.driverName.toLowerCase().includes(keyword) ||
        issue.taskInfo.machineryName.toLowerCase().includes(keyword)
      );
    }

    setFilteredIssues(filtered);
  };

  const handleViewDetail = (issue: TaskIssue & { taskInfo: DriverTask }) => {
    setSelectedIssue(issue);
    setShowDetailDialog(true);
  };

  const handleProcessIssue = (issue: TaskIssue & { taskInfo: DriverTask }) => {
    setSelectedIssue(issue);
    setHandleNote('');
    setHandleSolution('');
    setShowHandleDialog(true);
  };

  const onSubmitHandle = () => {
    if (!selectedIssue) return;

    if (!handleSolution.trim()) {
      toast.error('请填写处理方案');
      return;
    }

    // 更新问题状态
    const updatedTasks = tasks.map(task => {
      if (task.id === selectedIssue.taskInfo.id) {
        return {
          ...task,
          issues: task.issues.map(issue => {
            if (issue.id === selectedIssue.id) {
              return {
                ...issue,
                status: 'resolved',
                handledAt: new Date().toISOString(),
                handledBy: '管理员', // 实际应用中应该使用当前登录用户
                solution: handleSolution,
                handleNote: handleNote,
              };
            }
            return issue;
          }),
          updatedAt: new Date().toISOString(),
        };
      }
      return task;
    });

    setTasks(updatedTasks);
    localStorage.setItem('smart_agriculture_driver_tasks', JSON.stringify(updatedTasks));
    
    toast.success('问题处理成功');
    setShowHandleDialog(false);
    loadData();
  };

  // 状态转换为中文
  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '待处理';
      case 'processing':
        return '处理中';
      case 'resolved':
        return '已解决';
      case '待处理':
      case '处理中':
      case '已解决':
        return status;
      default:
        return status;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
      case '待处理':
        return 'bg-orange-100 text-orange-800';
      case 'resolved':
      case '已解决':
        return 'bg-green-100 text-green-800';
      case 'processing':
      case '处理中':
        return 'bg-blue-100 text-blue-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case '设备故障':
        return 'bg-red-100 text-red-800';
      case '地块问题':
        return 'bg-yellow-100 text-yellow-800';
      case '天气影响':
        return 'bg-blue-100 text-blue-800';
      case '作业困难':
        return 'bg-orange-100 text-orange-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const stats = {
    total: allIssues.length,
    pending: allIssues.filter(i => i.status === 'pending' || i.status === '待处理').length,
    processing: allIssues.filter(i => i.status === 'processing' || i.status === '处理中').length,
    resolved: allIssues.filter(i => i.status === 'resolved' || i.status === '已解决').length,
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">问题管理</h2>
          <p className="text-muted-foreground">查看和处理任务执行中上报的问题</p>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">问题总数</p>
              <p className="text-2xl mt-1">{stats.total}</p>
            </div>
            <MessageSquare className="w-8 h-8 text-blue-600" />
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">待处理</p>
              <p className="text-2xl mt-1 text-orange-600">{stats.pending}</p>
            </div>
            <AlertCircle className="w-8 h-8 text-orange-600" />
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">处理中</p>
              <p className="text-2xl mt-1 text-blue-600">{stats.processing}</p>
            </div>
            <Clock className="w-8 h-8 text-blue-600" />
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">已解决</p>
              <p className="text-2xl mt-1 text-green-600">{stats.resolved}</p>
            </div>
            <CheckCircle className="w-8 h-8 text-green-600" />
          </div>
        </Card>
      </div>

      {/* 筛选和搜索 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-muted-foreground" />
            <span className="text-sm">筛选</span>
          </div>
          
          <Select value={filterStatus} onValueChange={setFilterStatus}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="全部状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="待处理">待处理</SelectItem>
              <SelectItem value="pending">待处理</SelectItem>
              <SelectItem value="处理中">处理中</SelectItem>
              <SelectItem value="processing">处理中</SelectItem>
              <SelectItem value="已解决">已解决</SelectItem>
              <SelectItem value="resolved">已解决</SelectItem>
            </SelectContent>
          </Select>

          <Select value={filterType} onValueChange={setFilterType}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="全部类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="设备故障">设备故障</SelectItem>
              <SelectItem value="地块问题">地块问题</SelectItem>
              <SelectItem value="天气影响">天气影响</SelectItem>
              <SelectItem value="作业困难">作业困难</SelectItem>
              <SelectItem value="其他问题">其他问题</SelectItem>
            </SelectContent>
          </Select>

          <div className="flex-1 flex items-center gap-2">
            <Search className="w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索任务编号、驾驶员、农机或问题描述..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="max-w-md"
            />
          </div>

          {(filterStatus !== 'all' || filterType !== 'all' || searchKeyword) && (
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                setFilterStatus('all');
                setFilterType('all');
                setSearchKeyword('');
              }}
            >
              清除筛选
            </Button>
          )}
        </div>
      </Card>

      {/* 问题列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>上报时间</TableHead>
              <TableHead>任务编号</TableHead>
              <TableHead>驾驶员</TableHead>
              <TableHead>农机</TableHead>
              <TableHead>问题类型</TableHead>
              <TableHead>问题描述</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredIssues.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground h-32">
                  暂无问题上报
                </TableCell>
              </TableRow>
            ) : (
              filteredIssues.map((issue) => (
                <TableRow key={issue.id}>
                  <TableCell>
                    <div className="text-sm">
                      {new Date(issue.reportedAt).toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">{issue.taskInfo.taskNumber}</div>
                  </TableCell>
                  <TableCell>{issue.reportedBy}</TableCell>
                  <TableCell>{issue.taskInfo.machineryName}</TableCell>
                  <TableCell>
                    <Badge variant="outline" className={getTypeColor(issue.type)}>
                      {issue.type}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="max-w-xs truncate text-sm">
                      {issue.description}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="secondary" className={getStatusColor(issue.status)}>
                      {getStatusText(issue.status)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetail(issue)}
                        title="查看详情"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      {(issue.status === 'pending' || issue.status === '待处理') && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleProcessIssue(issue)}
                          title="处理问题"
                          className="text-green-600"
                        >
                          处理
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 问题详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>问题详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看问题的详细信息
            </DialogDescription>
          </DialogHeader>

          {selectedIssue && (
            <div className="space-y-4">
              {/* 任务信息 */}
              <Card className="p-4 bg-gray-50">
                <h4 className="mb-3">关联任务</h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">任务编号：</span>
                    <span>{selectedIssue.taskInfo.taskNumber}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">任务状态：</span>
                    <Badge variant="secondary" className="ml-2">
                      {selectedIssue.taskInfo.status}
                    </Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">驾驶员：</span>
                    <span>{selectedIssue.taskInfo.driverName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">农机设备：</span>
                    <span>{selectedIssue.taskInfo.machineryName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">作业地块：</span>
                    <span>{selectedIssue.taskInfo.fieldName || '-'}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">作业类型：</span>
                    <span>{selectedIssue.taskInfo.operationType}</span>
                  </div>
                </div>
              </Card>

              {/* 问题信息 */}
              <Card className="p-4">
                <h4 className="mb-3">问题信息</h4>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <div>
                      <Badge variant="outline" className={getTypeColor(selectedIssue.type)}>
                        {selectedIssue.type}
                      </Badge>
                      <span className="text-sm text-muted-foreground ml-3">
                        上报时间：{new Date(selectedIssue.reportedAt).toLocaleString('zh-CN')}
                      </span>
                    </div>
                    <Badge variant="secondary" className={getStatusColor(selectedIssue.status)}>
                      {getStatusText(selectedIssue.status)}
                    </Badge>
                  </div>

                  <div>
                    <div className="text-sm text-muted-foreground mb-1">问题描述</div>
                    <div className="p-3 bg-gray-50 rounded border">
                      {selectedIssue.description}
                    </div>
                  </div>

                  {selectedIssue.photos && selectedIssue.photos.length > 0 && (
                    <div>
                      <div className="text-sm text-muted-foreground mb-2">相关图片</div>
                      <div className="grid grid-cols-4 gap-2">
                        {selectedIssue.photos.map((photo, idx) => (
                          <img
                            key={idx}
                            src={photo}
                            alt={`问题图片${idx + 1}`}
                            className="w-full h-32 object-cover rounded border cursor-pointer hover:opacity-80"
                            onClick={() => window.open(photo, '_blank')}
                          />
                        ))}
                      </div>
                    </div>
                  )}

                  <div className="text-sm text-muted-foreground">
                    上报人：{selectedIssue.reportedBy}
                  </div>
                </div>
              </Card>

              {/* 处理信息 */}
              {(selectedIssue.status === 'resolved' || selectedIssue.status === '已解决') && selectedIssue.solution && (
                <Card className="p-4 border-green-200 bg-green-50">
                  <h4 className="mb-3 text-green-800">处理方案</h4>
                  <div className="space-y-2">
                    <div>
                      <div className="text-sm text-muted-foreground mb-1">解决方案</div>
                      <div className="p-3 bg-white rounded border">
                        {selectedIssue.solution}
                      </div>
                    </div>
                    {selectedIssue.handleNote && (
                      <div>
                        <div className="text-sm text-muted-foreground mb-1">处理备注</div>
                        <div className="p-3 bg-white rounded border">
                          {selectedIssue.handleNote}
                        </div>
                      </div>
                    )}
                    <div className="text-sm text-muted-foreground">
                      处理时间：{selectedIssue.handledAt && new Date(selectedIssue.handledAt).toLocaleString('zh-CN')}
                      {selectedIssue.handledBy && ` | 处理人：${selectedIssue.handledBy}`}
                    </div>
                  </div>
                </Card>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
            {selectedIssue && (selectedIssue.status === 'pending' || selectedIssue.status === '待处理') && (
              <Button
                onClick={() => {
                  setShowDetailDialog(false);
                  handleProcessIssue(selectedIssue);
                }}
              >
                立即处理
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 处理问题对话框 */}
      <Dialog open={showHandleDialog} onOpenChange={setShowHandleDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>处理问题</DialogTitle>
            <DialogDescription>
              请填写问题的处理方案和备注
            </DialogDescription>
          </DialogHeader>

          {selectedIssue && (
            <div className="space-y-4">
              {/* 问题摘要 */}
              <Card className="p-3 bg-gray-50">
                <div className="text-sm space-y-1">
                  <div>
                    <span className="text-muted-foreground">任务编号：</span>
                    <span>{selectedIssue.taskInfo.taskNumber}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">问题类型：</span>
                    <Badge variant="outline" className={`${getTypeColor(selectedIssue.type)} ml-2`}>
                      {selectedIssue.type}
                    </Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">问题描述：</span>
                    <span>{selectedIssue.description}</span>
                  </div>
                </div>
              </Card>

              {/* 处理表单 */}
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="solution">解决方案 *</Label>
                  <Textarea
                    id="solution"
                    value={handleSolution}
                    onChange={(e) => setHandleSolution(e.target.value)}
                    placeholder="请详细描述问题的解决方案..."
                    rows={4}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="handleNote">处理备注（可选）</Label>
                  <Textarea
                    id="handleNote"
                    value={handleNote}
                    onChange={(e) => setHandleNote(e.target.value)}
                    placeholder="补充说明或注意事项..."
                    rows={3}
                  />
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowHandleDialog(false)}>
              取消
            </Button>
            <Button onClick={onSubmitHandle}>
              确认处理
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
