import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Textarea } from '../ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '../ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog';
import { Plus, Edit, Trash2, Search, MapPin } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface UsageScenario {
  id: string;
  name: string;
  code: string;
  description: string;
  applicableTypes: string[];
  count: number;
  createdAt: string;
  updatedAt: string;
}

const STORAGE_KEY = 'usage_scenarios';

export function UsageScenarioManagement() {
  const [scenarios, setScenarios] = useState<UsageScenario[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showDialog, setShowDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingScenario, setEditingScenario] = useState<UsageScenario | null>(null);
  const [deletingScenario, setDeletingScenario] = useState<UsageScenario | null>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    description: '',
  });

  // 初始化数据
  useEffect(() => {
    loadScenarios();
  }, []);

  const loadScenarios = () => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      setScenarios(JSON.parse(stored));
    } else {
      // 初始化默认数据
      const defaultScenarios: UsageScenario[] = [
        {
          id: 'scenario-1',
          name: '耕地作业',
          code: 'GDZY',
          description: '用于农田耕作、翻地、起垄等作业',
          applicableTypes: ['拖拉机', '耕地机'],
          count: 12,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'scenario-2',
          name: '播种作业',
          code: 'BZZY',
          description: '用于各类作物的播种、点播、条播等作业',
          applicableTypes: ['播种机', '拖拉机'],
          count: 8,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'scenario-3',
          name: '植保作业',
          code: 'ZBZY',
          description: '用于农作物病虫害防治、施药等作业',
          applicableTypes: ['植保机', '无人机'],
          count: 6,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'scenario-4',
          name: '收获作业',
          code: 'SHZY',
          description: '用于农作物的收割、脱粒、清选等作业',
          applicableTypes: ['收割机', '脱粒机'],
          count: 10,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'scenario-5',
          name: '灌溉作业',
          code: 'GGZY',
          description: '用于农田灌溉、喷灌、滴灌等作业',
          applicableTypes: ['灌溉设备', '水泵'],
          count: 5,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'scenario-6',
          name: '运输作业',
          code: 'YSZY',
          description: '用于农产品、农资等物资的运输作业',
          applicableTypes: ['拖拉机', '运输车'],
          count: 7,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem(STORAGE_KEY, JSON.stringify(defaultScenarios));
      setScenarios(defaultScenarios);
    }
  };

  const saveScenarios = (updatedScenarios: UsageScenario[]) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedScenarios));
    setScenarios(updatedScenarios);
  };

  // 过滤场景
  const filteredScenarios = scenarios.filter(scenario =>
    scenario.name.includes(searchKeyword) ||
    scenario.code.includes(searchKeyword) ||
    scenario.description.includes(searchKeyword)
  );

  // 打开新增对话框
  const handleAdd = () => {
    setEditingScenario(null);
    setFormData({ name: '', code: '', description: '' });
    setShowDialog(true);
  };

  // 打开编辑对话框
  const handleEdit = (scenario: UsageScenario) => {
    setEditingScenario(scenario);
    setFormData({
      name: scenario.name,
      code: scenario.code,
      description: scenario.description,
    });
    setShowDialog(true);
  };

  // 保存场景
  const handleSave = () => {
    if (!formData.name.trim()) {
      toast.error('请输入场景名称');
      return;
    }
    if (!formData.code.trim()) {
      toast.error('请输入场景编码');
      return;
    }

    const now = new Date().toISOString();

    if (editingScenario) {
      // 编辑
      const updatedScenarios = scenarios.map(scenario =>
        scenario.id === editingScenario.id
          ? { ...scenario, ...formData, updatedAt: now }
          : scenario
      );
      saveScenarios(updatedScenarios);
      toast.success('使用场景更新成功');
    } else {
      // 新增
      const newScenario: UsageScenario = {
        id: `scenario-${Date.now()}`,
        ...formData,
        applicableTypes: [],
        count: 0,
        createdAt: now,
        updatedAt: now,
      };
      saveScenarios([...scenarios, newScenario]);
      toast.success('使用场景添加成功');
    }

    setShowDialog(false);
  };

  // 打开删除确认对话框
  const handleDeleteClick = (scenario: UsageScenario) => {
    setDeletingScenario(scenario);
    setShowDeleteDialog(true);
  };

  // 删除场景
  const handleDelete = () => {
    if (deletingScenario) {
      const updatedScenarios = scenarios.filter(scenario => scenario.id !== deletingScenario.id);
      saveScenarios(updatedScenarios);
      toast.success('使用场景删除成功');
      setShowDeleteDialog(false);
      setDeletingScenario(null);
    }
  };

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <div className="space-y-6">
      {/* 搜索和操作栏 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索使用场景..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Button
            className="bg-green-600 hover:bg-green-700"
            onClick={handleAdd}
          >
            <Plus className="w-4 h-4 mr-2" />
            新增场景
          </Button>
        </div>
      </Card>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">场景总数</p>
              <p className="mt-2 text-2xl text-green-600">{scenarios.length}</p>
            </div>
            <MapPin className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">设备总数</p>
              <p className="mt-2 text-2xl text-blue-600">
                {scenarios.reduce((sum, scenario) => sum + scenario.count, 0)}
              </p>
            </div>
            <MapPin className="w-12 h-12 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">使用最多</p>
              <p className="mt-2 text-sm text-purple-600">
                {scenarios.length > 0
                  ? scenarios.reduce((max, scenario) => (scenario.count > max.count ? scenario : max)).name
                  : '-'}
              </p>
            </div>
            <MapPin className="w-12 h-12 text-purple-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">最近更新</p>
              <p className="mt-2 text-xs text-orange-600">
                {scenarios.length > 0
                  ? new Date(Math.max(...scenarios.map(s => new Date(s.updatedAt).getTime()))).toLocaleDateString('zh-CN')
                  : '-'}
              </p>
            </div>
            <MapPin className="w-12 h-12 text-orange-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 场景列表 */}
      <Card>
        <div className="p-6">
          <h3 className="text-green-800 mb-4">使用场景列表</h3>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>场景编码</TableHead>
                <TableHead>场景名称</TableHead>
                <TableHead>描述</TableHead>
                <TableHead>设备数量</TableHead>
                <TableHead>更新时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredScenarios.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                    {searchKeyword ? '未找到匹配的场景' : '暂无使用场景数据'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredScenarios.map((scenario) => (
                  <TableRow key={scenario.id}>
                    <TableCell>
                      <Badge variant="outline">{scenario.code}</Badge>
                    </TableCell>
                    <TableCell className="font-medium">{scenario.name}</TableCell>
                    <TableCell className="text-muted-foreground max-w-xs truncate">
                      {scenario.description || '-'}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{scenario.count} 台</Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {formatDate(scenario.updatedAt)}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleEdit(scenario)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteClick(scenario)}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* 新增/编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingScenario ? '编辑使用场景' : '新增使用场景'}</DialogTitle>
            <DialogDescription>
              {editingScenario ? '修改使用场景信息' : '添加新的使用场景'}
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="code">场景编码 *</Label>
              <Input
                id="code"
                placeholder="如：GDZY"
                value={formData.code}
                onChange={(e) => setFormData({ ...formData, code: e.target.value.toUpperCase() })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="name">场景名称 *</Label>
              <Input
                id="name"
                placeholder="如：耕地作业"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">描述</Label>
              <Textarea
                id="description"
                placeholder="请输入场景描述..."
                rows={3}
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除使用场景 <span className="font-semibold">"{deletingScenario?.name}"</span> 吗？
              {deletingScenario && deletingScenario.count > 0 && (
                <span className="block mt-2 text-orange-600">
                  注意：该场景下还有 {deletingScenario.count} 台设备！
                </span>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={handleDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
