import { useState, useEffect } from 'react';
import { MachineryRecord, MachineryFilter } from '../../types/machinery';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog';
import { Edit, Trash2, QrCode, Eye, Search } from 'lucide-react';
import { Card } from '../ui/card';
import { usePagination } from '../../lib/usePagination';
import { DataPagination } from '../ui/data-pagination';

interface MachineryListProps {
  machinery: MachineryRecord[];
  tags: { id: string; name: string; color: string }[];
  onEdit: (machinery: MachineryRecord) => void;
  onDelete: (id: string) => void;
  onViewQRCode: (machinery: MachineryRecord) => void;
  onViewDetails: (machinery: MachineryRecord) => void;
}

export function MachineryList({ 
  machinery, 
  tags,
  onEdit, 
  onDelete, 
  onViewQRCode,
  onViewDetails 
}: MachineryListProps) {
  const [filter, setFilter] = useState<MachineryFilter>({});
  const [availableCategories, setAvailableCategories] = useState<string[]>(['耕地机械', '播种机械', '收获机械', '植保机械', '灌溉机械', '运输机械', '其他']);
  const [availableUsages, setAvailableUsages] = useState<string[]>(['旱地', '水田', '通用', '其他']);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string>('');

  const handleDeleteClick = (id: string) => {
    setDeletingId(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    onDelete(deletingId);
    setDeleteDialogOpen(false);
    setDeletingId('');
  };

  // 从 localStorage 加载农机类型和使用场景
  useEffect(() => {
    // 加载农机类型
    const storedTypes = localStorage.getItem('machinery_types');
    if (storedTypes) {
      try {
        const types = JSON.parse(storedTypes);
        const typeNames = types.map((t: any) => t.name);
        // 合并预置类型和自定义类型，去重
        const allCategories = Array.from(new Set([...typeNames, '其他']));
        setAvailableCategories(allCategories);
      } catch (e) {
        console.error('Failed to load machinery types:', e);
      }
    }

    // 加载使用场景
    const storedScenarios = localStorage.getItem('usage_scenarios');
    if (storedScenarios) {
      try {
        const scenarios = JSON.parse(storedScenarios);
        const scenarioNames = scenarios.map((s: any) => s.name);
        // 合并预置场景和自定义场景，去重
        const allUsages = Array.from(new Set([...scenarioNames, '其他']));
        setAvailableUsages(allUsages);
      } catch (e) {
        console.error('Failed to load usage scenarios:', e);
      }
    }
  }, [machinery]); // 当设备列表更新时重新加载

  const getStatusColor = (status: string) => {
    switch (status) {
      case '正常': return 'bg-success-muted text-success';
      case '待维护': return 'bg-warning-muted text-warning';
      case '已报废': return 'bg-error-muted text-error';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const filteredMachinery = machinery.filter(m => {
    if (filter.category && m.category !== filter.category) return false;
    if (filter.usage && m.usage !== filter.usage) return false;
    if (filter.status && m.status !== filter.status) return false;
    if (filter.tags && filter.tags.length > 0) {
      if (!filter.tags.some(tag => m.tags.includes(tag))) return false;
    }
    if (filter.searchKeyword) {
      const keyword = filter.searchKeyword.toLowerCase();
      return (
        m.name.toLowerCase().includes(keyword) ||
        m.model.toLowerCase().includes(keyword) ||
        m.engineNumber.toLowerCase().includes(keyword) ||
        m.chassisNumber.toLowerCase().includes(keyword)
      );
    }
    return true;
  });

  // 分页
  const pagination = usePagination(filteredMachinery, 10);

  return (
    <div className="space-y-4">
      {/* 筛选栏 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <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={filter.searchKeyword || ''}
              onChange={(e) => setFilter({ ...filter, searchKeyword: e.target.value })}
              className="pl-9"
            />
          </div>

          <Select
            value={filter.category || 'all'}
            onValueChange={(value) => setFilter({ ...filter, category: value === 'all' ? undefined : value as any })}
          >
            <SelectTrigger>
              <SelectValue placeholder="农机类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              {availableCategories.map(category => (
                <SelectItem key={category} value={category}>{category}</SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select
            value={filter.usage || 'all'}
            onValueChange={(value) => setFilter({ ...filter, usage: value === 'all' ? undefined : value as any })}
          >
            <SelectTrigger>
              <SelectValue placeholder="使用场景" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部场景</SelectItem>
              {availableUsages.map(usage => (
                <SelectItem key={usage} value={usage}>{usage}</SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select
            value={filter.status || 'all'}
            onValueChange={(value) => setFilter({ ...filter, status: value === 'all' ? undefined : value as any })}
          >
            <SelectTrigger>
              <SelectValue placeholder="设备状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="正常">正常</SelectItem>
              <SelectItem value="待维护">待维护</SelectItem>
              <SelectItem value="已报废">已报废</SelectItem>
            </SelectContent>
          </Select>

          <Button 
            variant="outline" 
            onClick={() => setFilter({})}
          >
            清空筛选
          </Button>
        </div>

        {/* 标签筛选 */}
        {tags.length > 0 && (
          <div className="mt-4">
            <div className="text-sm mb-2">按标签筛选：</div>
            <div className="flex flex-wrap gap-2">
              {tags.map(tag => (
                <Badge
                  key={tag.id}
                  variant={filter.tags?.includes(tag.id) ? "default" : "outline"}
                  className="cursor-pointer"
                  style={filter.tags?.includes(tag.id) ? { backgroundColor: tag.color } : {}}
                  onClick={() => {
                    const currentTags = filter.tags || [];
                    setFilter({
                      ...filter,
                      tags: currentTags.includes(tag.id)
                        ? currentTags.filter(t => t !== tag.id)
                        : [...currentTags, tag.id]
                    });
                  }}
                >
                  {tag.name}
                </Badge>
              ))}
            </div>
          </div>
        )}
      </Card>

      {/* 列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>设备名称</TableHead>
              <TableHead>型号</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>场景</TableHead>
              <TableHead>发动机号</TableHead>
              <TableHead>车架号</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>标签</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {pagination.paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              pagination.paginatedData.map((item) => {
                const itemTags = tags.filter(tag => item.tags.includes(tag.id));
                return (
                  <TableRow key={item.id}>
                    <TableCell>{item.name}</TableCell>
                    <TableCell>{item.model}</TableCell>
                    <TableCell>{item.category}</TableCell>
                    <TableCell>{item.usage}</TableCell>
                    <TableCell>{item.engineNumber}</TableCell>
                    <TableCell>{item.chassisNumber}</TableCell>
                    <TableCell>
                      <Badge variant="secondary" className={getStatusColor(item.status)}>
                        {item.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {itemTags.map(tag => (
                          <Badge key={tag.id} variant="outline" style={{ borderColor: tag.color, color: tag.color }}>
                            {tag.name}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button variant="ghost" size="sm" onClick={() => onViewDetails(item)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => onViewQRCode(item)}>
                          <QrCode className="w-4 h-4" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => onEdit(item)}>
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          onClick={() => handleDeleteClick(item.id)}
                        >
                          <Trash2 className="w-4 h-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>

        {/* 分页 */}
        <DataPagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          pageSize={pagination.pageSize}
          totalItems={filteredMachinery.length}
          startIndex={pagination.startIndex}
          endIndex={pagination.endIndex}
          onPageChange={pagination.goToPage}
          onPageSizeChange={pagination.setPageSize}
          canPreviousPage={pagination.canPreviousPage}
          canNextPage={pagination.canNextPage}
        />

        <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>确认删除</AlertDialogTitle>
              <AlertDialogDescription>
                确定要删除这条农机记录吗？此操作无法撤销。
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>取消</AlertDialogCancel>
              <AlertDialogAction
                className="bg-error hover:bg-error/90"
                onClick={confirmDelete}
              >
                删除
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </Card>
    </div>
  );
}
