import { useState, useEffect } from 'react';
import { MaintenanceRecord, MaintenanceType, Material, MaterialUsage } from '../../types/machinery';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
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 { Badge } from '../ui/badge';
import { Checkbox } from '../ui/checkbox';
import { Plus, Edit, Trash2, Wrench, Calendar, DollarSign, Package } from 'lucide-react';
import { machineryStorage } from '../../lib/machineryStorage';
import { materialStorage, initializeMaterialData } from '../../lib/materialStorage';
import { toast } from 'sonner@2.0.3';

interface MaintenanceRecordsProps {
  machineryId: string;
  machineryName: string;
}

export function MaintenanceRecords({ machineryId, machineryName }: MaintenanceRecordsProps) {
  const [records, setRecords] = useState<MaintenanceRecord[]>(
    machineryStorage.getMaintenanceRecords(machineryId)
  );
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingRecord, setEditingRecord] = useState<MaintenanceRecord | null>(null);
  const [availableMaterials, setAvailableMaterials] = useState<Material[]>([]);

  const [formData, setFormData] = useState<Partial<MaintenanceRecord>>({
    type: '日常保养',
    startTime: '',
    endTime: '',
    workHours: 0,
    maintenanceItems: '',
    partsAndMaterials: [],
    cost: 0,
    technician: '',
  });

  // 初始化农资数据
  useEffect(() => {
    initializeMaterialData();
    setAvailableMaterials(materialStorage.getAvailableMaterials());
  }, []);

  const handleOpenForm = (record?: MaintenanceRecord) => {
    if (record) {
      setEditingRecord(record);
      setFormData(record);
    } else {
      setEditingRecord(null);
      setFormData({
        type: '日常保养',
        startTime: '',
        endTime: '',
        workHours: 0,
        maintenanceItems: '',
        partsAndMaterials: [],
        cost: 0,
        technician: '',
      });
    }
    setIsFormOpen(true);
  };

  const handleCloseForm = () => {
    setIsFormOpen(false);
    setEditingRecord(null);
    setFormData({
      type: '日常保养',
      startTime: '',
      endTime: '',
      workHours: 0,
      maintenanceItems: '',
      partsAndMaterials: [],
      cost: 0,
      technician: '',
    });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.startTime || !formData.endTime || !formData.maintenanceItems || !formData.technician) {
      toast.error('请填写必填项');
      return;
    }

    const record: MaintenanceRecord = {
      id: editingRecord?.id || `maintenance-${Date.now()}`,
      machineryId,
      type: formData.type as MaintenanceType,
      startTime: formData.startTime!,
      endTime: formData.endTime!,
      workHours: formData.workHours || 0,
      nextMaintenanceTime: formData.nextMaintenanceTime,
      maintenanceItems: formData.maintenanceItems!,
      partsAndMaterials: formData.partsAndMaterials,
      cost: formData.cost || 0,
      technician: formData.technician!,
      remarks: formData.remarks,
      createdAt: editingRecord?.createdAt || new Date().toISOString(),
      createdBy: editingRecord?.createdBy || '当前用户',
    };

    machineryStorage.saveMaintenanceRecord(record);
    setRecords(machineryStorage.getMaintenanceRecords(machineryId));
    toast.success(editingRecord ? '维护记录已更新' : '维护记录已添加');
    handleCloseForm();
  };

  const handleDelete = (id: string) => {
    if (confirm('确定要删除这条维护记录吗？')) {
      machineryStorage.deleteMaintenanceRecord(id);
      setRecords(machineryStorage.getMaintenanceRecords(machineryId));
      toast.success('维护记录已删除');
    }
  };

  const getTypeColor = (type: MaintenanceType) => {
    switch (type) {
      case '日常保养': return 'bg-blue-100 text-blue-700';
      case '定期维护': return 'bg-green-100 text-green-700';
      case '故障维修': return 'bg-red-100 text-red-700';
      case '年检': return 'bg-purple-100 text-purple-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

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

  const formatCurrency = (amount: number) => {
    return `¥${amount.toLocaleString()}`;
  };

  // 统计数据
  const stats = {
    total: records.length,
    totalCost: records.reduce((sum, r) => sum + r.cost, 0),
    totalHours: records.reduce((sum, r) => sum + r.workHours, 0),
    byType: {
      '日常保养': records.filter(r => r.type === '日常保养').length,
      '定期维护': records.filter(r => r.type === '定期维护').length,
      '故障维修': records.filter(r => r.type === '故障维修').length,
      '年检': records.filter(r => r.type === '年检').length,
    }
  };

  return (
    <div className="space-y-4">
      {/* 统计卡片 */}
      <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-blue-600">{stats.total}</p>
              <p className="text-xs text-blue-600 mt-1">次</p>
            </div>
            <Wrench 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-2xl text-green-600">{formatCurrency(stats.totalCost)}</p>
              <p className="text-xs text-green-600 mt-1">累计支出</p>
            </div>
            <DollarSign 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-orange-600">{stats.totalHours}</p>
              <p className="text-xs text-orange-600 mt-1">小时</p>
            </div>
            <Calendar className="w-12 h-12 text-orange-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div>
            <p className="text-xs text-muted-foreground mb-2">维护类型分布</p>
            <div className="space-y-1">
              <div className="flex justify-between text-xs">
                <span>日常保养</span>
                <span className="text-blue-600">{stats.byType['日常保养']}</span>
              </div>
              <div className="flex justify-between text-xs">
                <span>定期维护</span>
                <span className="text-green-600">{stats.byType['定期维护']}</span>
              </div>
              <div className="flex justify-between text-xs">
                <span>故障维修</span>
                <span className="text-red-600">{stats.byType['故障维修']}</span>
              </div>
              <div className="flex justify-between text-xs">
                <span>年检</span>
                <span className="text-purple-600">{stats.byType['年检']}</span>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* 操作按钮 */}
      <div className="flex justify-between items-center">
        <h4 className="text-green-800">维护记录列表</h4>
        <Button onClick={() => handleOpenForm()}>
          <Plus className="w-4 h-4 mr-2" />
          新增维护记录
        </Button>
      </div>

      {/* 维护记录列表 */}
      <Card>
        {records.length === 0 ? (
          <div className="p-8 text-center text-muted-foreground">
            暂无维护记录，点击"新增维护记录"开始记录
          </div>
        ) : (
          <div className="overflow-x-auto">
            <Table className="min-w-[900px]">
            <TableHeader>
              <TableRow>
                <TableHead>维护类型</TableHead>
                <TableHead>维护时间</TableHead>
                <TableHead>工时</TableHead>
                <TableHead>维护项目</TableHead>
                <TableHead>维护人员</TableHead>
                <TableHead>费用</TableHead>
                <TableHead>下次维护</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {records.map((record) => (
                <TableRow key={record.id}>
                  <TableCell>
                    <Badge className={getTypeColor(record.type)}>
                      {record.type}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div>{formatDate(record.startTime)}</div>
                      <div className="text-xs text-muted-foreground">
                        至 {formatDate(record.endTime)}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{record.workHours}h</TableCell>
                  <TableCell>
                    <div className="max-w-xs">
                      <div className="truncate" title={record.maintenanceItems}>
                        {record.maintenanceItems}
                      </div>
                      {record.partsAndMaterials && record.partsAndMaterials.length > 0 && (
                        <div className="text-xs text-muted-foreground mt-1">
                          使用配件：{record.partsAndMaterials.map(usage => {
                            const material = materialStorage.getMaterial(usage.materialId);
                            return material ? `${material.name} × ${usage.quantity}${material.unit}` : null;
                          }).filter(Boolean).join('、')}
                        </div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>{record.technician}</TableCell>
                  <TableCell>{formatCurrency(record.cost)}</TableCell>
                  <TableCell>
                    {record.nextMaintenanceTime ? (
                      <div className="text-sm">
                        {new Date(record.nextMaintenanceTime).toLocaleDateString('zh-CN')}
                      </div>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => handleOpenForm(record)}
                      >
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => handleDelete(record.id)}
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          </div>
        )}
      </Card>

      {/* 新增/编辑表单 */}
      <Dialog open={isFormOpen} onOpenChange={handleCloseForm}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingRecord ? '编辑维护记录' : '新增维护记录'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingRecord ? '编辑' : '新增'}维护记录表单
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="type">
                  维护类型 <span className="text-red-500">*</span>
                </Label>
                <Select
                  value={formData.type}
                  onValueChange={(value) => setFormData({ ...formData, type: value as MaintenanceType })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="日常保养">日常保养</SelectItem>
                    <SelectItem value="定期维护">定期维护</SelectItem>
                    <SelectItem value="故障维修">故障维修</SelectItem>
                    <SelectItem value="年检">年检</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="technician">
                  维护人员 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="technician"
                  value={formData.technician}
                  onChange={(e) => setFormData({ ...formData, technician: e.target.value })}
                  placeholder="请输入维护人员"
                  required
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="startTime">
                  维护开始时间 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="startTime"
                  type="datetime-local"
                  value={formData.startTime}
                  onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
                  required
                />
              </div>

              <div>
                <Label htmlFor="endTime">
                  维护结束时间 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="endTime"
                  type="datetime-local"
                  value={formData.endTime}
                  onChange={(e) => setFormData({ ...formData, endTime: e.target.value })}
                  required
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="workHours">维护工时（小时）</Label>
                <Input
                  id="workHours"
                  type="number"
                  min="0"
                  step="0.5"
                  value={formData.workHours}
                  onChange={(e) => setFormData({ ...formData, workHours: parseFloat(e.target.value) || 0 })}
                  placeholder="请输入工时"
                />
              </div>

              <div>
                <Label htmlFor="cost">维护费用（元）</Label>
                <Input
                  id="cost"
                  type="number"
                  min="0"
                  step="0.01"
                  value={formData.cost}
                  onChange={(e) => setFormData({ ...formData, cost: parseFloat(e.target.value) || 0 })}
                  placeholder="请输入费用"
                />
              </div>
            </div>

            <div>
              <Label htmlFor="nextMaintenanceTime">下次维护时间</Label>
              <Input
                id="nextMaintenanceTime"
                type="date"
                value={formData.nextMaintenanceTime}
                onChange={(e) => setFormData({ ...formData, nextMaintenanceTime: e.target.value })}
              />
            </div>

            <div>
              <Label htmlFor="maintenanceItems">
                维护项目 <span className="text-red-500">*</span>
              </Label>
              <Textarea
                id="maintenanceItems"
                value={formData.maintenanceItems}
                onChange={(e) => setFormData({ ...formData, maintenanceItems: e.target.value })}
                placeholder="请详细描述维护项目内容"
                rows={3}
                required
              />
            </div>

            <div>
              <Label htmlFor="partsAndMaterials">
                <Package className="w-4 h-4 inline mr-1" />
                配件与耗材
              </Label>
              <Card className="p-4 mt-2 max-h-80 overflow-y-auto">
                {availableMaterials.length === 0 ? (
                  <p className="text-sm text-muted-foreground text-center py-4">
                    暂无可用的配件与耗材
                  </p>
                ) : (
                  <div className="space-y-3">
                    {availableMaterials.map((material) => {
                      const usage = formData.partsAndMaterials?.find(u => u.materialId === material.id);
                      const isChecked = !!usage;
                      
                      return (
                        <div key={material.id} className="border rounded-lg p-3 hover:bg-muted/50 transition-colors">
                          <div className="flex items-start space-x-2">
                            <Checkbox
                              id={`material-${material.id}`}
                              checked={isChecked}
                              onCheckedChange={(checked) => {
                                const current = formData.partsAndMaterials || [];
                                if (checked) {
                                  setFormData({
                                    ...formData,
                                    partsAndMaterials: [...current, { materialId: material.id, quantity: 1 }]
                                  });
                                } else {
                                  setFormData({
                                    ...formData,
                                    partsAndMaterials: current.filter(u => u.materialId !== material.id)
                                  });
                                }
                              }}
                            />
                            <div className="flex-1">
                              <label
                                htmlFor={`material-${material.id}`}
                                className="cursor-pointer block"
                              >
                                <div className="flex items-center justify-between">
                                  <div className="flex items-center gap-2">
                                    <span className="text-sm">{material.name}</span>
                                    <Badge variant="outline" className="text-xs">
                                      {material.type}
                                    </Badge>
                                    <span className="text-xs text-muted-foreground">
                                      {material.spec}
                                    </span>
                                  </div>
                                  <div className="text-xs text-muted-foreground">
                                    库存: {material.currentStock} {material.unit}
                                  </div>
                                </div>
                                <div className="text-xs text-muted-foreground mt-1">
                                  {material.supplier} | ¥{material.purchasePrice}/{material.unit}
                                </div>
                              </label>
                              
                              {isChecked && (
                                <div className="mt-2 flex items-center gap-2">
                                  <Label htmlFor={`quantity-${material.id}`} className="text-xs">
                                    使用数量:
                                  </Label>
                                  <Input
                                    id={`quantity-${material.id}`}
                                    type="number"
                                    min="0.01"
                                    step="0.01"
                                    max={material.currentStock}
                                    value={usage?.quantity || 1}
                                    onChange={(e) => {
                                      const quantity = parseFloat(e.target.value) || 1;
                                      const current = formData.partsAndMaterials || [];
                                      setFormData({
                                        ...formData,
                                        partsAndMaterials: current.map(u => 
                                          u.materialId === material.id 
                                            ? { ...u, quantity } 
                                            : u
                                        )
                                      });
                                    }}
                                    className="w-24 h-8 text-sm"
                                    placeholder="数量"
                                  />
                                  <span className="text-xs text-muted-foreground">
                                    {material.unit}
                                  </span>
                                  <span className="text-xs text-muted-foreground ml-auto">
                                    小计: ¥{((usage?.quantity || 1) * material.purchasePrice).toFixed(2)}
                                  </span>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </Card>
              {formData.partsAndMaterials && formData.partsAndMaterials.length > 0 && (
                <div className="mt-2 space-y-1">
                  <div className="text-sm text-muted-foreground">
                    已选择 {formData.partsAndMaterials.length} 项配件与耗材
                  </div>
                  <div className="text-sm">
                    预估配件费用: ¥{formData.partsAndMaterials.reduce((sum, usage) => {
                      const material = availableMaterials.find(m => m.id === usage.materialId);
                      return sum + (material ? material.purchasePrice * usage.quantity : 0);
                    }, 0).toFixed(2)}
                  </div>
                </div>
              )}
            </div>

            <div>
              <Label htmlFor="remarks">备注</Label>
              <Textarea
                id="remarks"
                value={formData.remarks}
                onChange={(e) => setFormData({ ...formData, remarks: e.target.value })}
                placeholder="其他说明信息"
                rows={2}
              />
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <Button type="button" variant="outline" onClick={handleCloseForm}>
                取消
              </Button>
              <Button type="submit">
                {editingRecord ? '保存' : '添加'}
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
