import { useForm } from 'react-hook-form@7.55.0';
import { MachineryRecord, MachineryCategory, MachineryUsage, MachineryStatus } from '../../types/machinery';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Textarea } from '../ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Upload, X } from 'lucide-react';
import { useState, useEffect } from 'react';
import { Badge } from '../ui/badge';

interface MachineryFormProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: Partial<MachineryRecord>) => void;
  initialData?: MachineryRecord;
  availableTags: { id: string; name: string; color: string }[];
}

export function MachineryForm({ open, onClose, onSave, initialData, availableTags }: MachineryFormProps) {
  const { register, handleSubmit, setValue, watch, formState: { errors } } = useForm({
    defaultValues: initialData || {
      tags: [],
      status: '正常' as MachineryStatus,
    }
  });

  const [selectedTags, setSelectedTags] = useState<string[]>(initialData?.tags || []);
  const [invoiceFile, setInvoiceFile] = useState<string | undefined>(initialData?.invoiceUrl);
  const [categories, setCategories] = useState<string[]>(['耕地机械', '播种机械', '收获机械', '植保机械', '灌溉机械', '运输机械', '其他']);
  const [usages, setUsages] = useState<string[]>(['旱地', '水田', '通用', '其他']);
  const statuses: MachineryStatus[] = ['正常', '待维护', '已报废'];

  // 从 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, '其他']));
        setCategories(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, '其他']));
        setUsages(allUsages);
      } catch (e) {
        console.error('Failed to load usage scenarios:', e);
      }
    }
  }, [open]); // 每次打开对话框时重新加载

  const onSubmit = (data: any) => {
    onSave({
      ...data,
      tags: selectedTags,
      invoiceUrl: invoiceFile,
    });
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 模拟文件上传，实际应该上传到服务器
      const reader = new FileReader();
      reader.onloadend = () => {
        setInvoiceFile(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const toggleTag = (tagId: string) => {
    setSelectedTags(prev => 
      prev.includes(tagId) 
        ? prev.filter(t => t !== tagId)
        : [...prev, tagId]
    );
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{initialData ? '编辑农机档案' : '新增农机档案'}</DialogTitle>
          <DialogDescription className="sr-only">
            {initialData ? '编辑农机设备信息' : '新增农机设备信息'}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)}>
          <Tabs defaultValue="basic" className="w-full">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="basic">基本信息</TabsTrigger>
              <TabsTrigger value="technical">技术参数</TabsTrigger>
              <TabsTrigger value="purchase">购机信息</TabsTrigger>
              <TabsTrigger value="insurance">保险信息</TabsTrigger>
            </TabsList>

            {/* 基本信息 */}
            <TabsContent value="basic" className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="name">设备名称 *</Label>
                  <Input id="name" {...register('name', { required: true })} />
                  {errors.name && <span className="text-sm text-destructive">必填项</span>}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="model">型号规格 *</Label>
                  <Input id="model" {...register('model', { required: true })} />
                  {errors.model && <span className="text-sm text-destructive">必填项</span>}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="category">农机类型 *</Label>
                  <Select 
                    defaultValue={initialData?.category}
                    onValueChange={(value) => setValue('category', value as MachineryCategory)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择类型" />
                    </SelectTrigger>
                    <SelectContent>
                      {categories.map(cat => (
                        <SelectItem key={cat} value={cat}>{cat}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">
                    可在"分类管理"中添加自定义类型
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="usage">使用场景 *</Label>
                  <Select 
                    defaultValue={initialData?.usage}
                    onValueChange={(value) => setValue('usage', value as MachineryUsage)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择场景" />
                    </SelectTrigger>
                    <SelectContent>
                      {usages.map(usage => (
                        <SelectItem key={usage} value={usage}>{usage}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">
                    可在"分类管理"中添加自定义场景
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="manufacturer">生产厂家</Label>
                  <Input id="manufacturer" {...register('manufacturer')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="manufactureDate">出厂日期</Label>
                  <Input id="manufactureDate" type="date" {...register('manufactureDate')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="purchaseDate">购买日期</Label>
                  <Input id="purchaseDate" type="date" {...register('purchaseDate')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="status">设备状态</Label>
                  <Select 
                    defaultValue={initialData?.status || '正常'}
                    onValueChange={(value) => setValue('status', value as MachineryStatus)}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {statuses.map(status => (
                        <SelectItem key={status} value={status}>{status}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 保养周期 */}
              <div className="space-y-2">
                <Label>保养周期</Label>
                <div className="flex gap-2">
                  <div className="flex-1">
                    <Input 
                      type="number" 
                      min="1"
                      placeholder="输入周期"
                      {...register('maintenanceCycle')} 
                    />
                  </div>
                  <div className="w-32">
                    <Select 
                      defaultValue={initialData?.maintenanceCycleUnit || 'month'}
                      onValueChange={(value) => setValue('maintenanceCycleUnit', value as 'day' | 'month' | 'year')}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="day">天</SelectItem>
                        <SelectItem value="month">月</SelectItem>
                        <SelectItem value="year">年</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">设置设备的保养周期，用于自动提醒</p>
              </div>

              <div className="space-y-2">
                <Label>标签</Label>
                <div className="flex flex-wrap gap-2 border rounded-md p-3">
                  {availableTags.map(tag => (
                    <Badge
                      key={tag.id}
                      variant={selectedTags.includes(tag.id) ? "default" : "outline"}
                      className="cursor-pointer"
                      onClick={() => toggleTag(tag.id)}
                      style={selectedTags.includes(tag.id) ? { backgroundColor: tag.color } : {}}
                    >
                      {tag.name}
                    </Badge>
                  ))}
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="remarks">备注</Label>
                <Textarea id="remarks" {...register('remarks')} rows={3} />
              </div>
            </TabsContent>

            {/* 技术参数 */}
            <TabsContent value="technical" className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="engineNumber">发动机号 *</Label>
                  <Input id="engineNumber" {...register('engineNumber', { required: true })} />
                  {errors.engineNumber && <span className="text-sm text-destructive">必填项</span>}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="chassisNumber">车架号 *</Label>
                  <Input id="chassisNumber" {...register('chassisNumber', { required: true })} />
                  {errors.chassisNumber && <span className="text-sm text-destructive">必填项</span>}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="power">额定功率 (kW)</Label>
                  <Input id="power" {...register('power')} placeholder="例：55" />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="weight">整机重量 (kg)</Label>
                  <Input id="weight" {...register('weight')} placeholder="例：1500" />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="workingWidth">工作幅宽 (m)</Label>
                  <Input id="workingWidth" {...register('workingWidth')} placeholder="例：2.5" />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="fuelTankCapacity">油箱大小 (L)</Label>
                  <Input id="fuelTankCapacity" {...register('fuelTankCapacity')} placeholder="例：200" />
                </div>
              </div>
            </TabsContent>

            {/* 购机信息 */}
            <TabsContent value="purchase" className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="purchasePrice">购机价格 (元)</Label>
                  <Input 
                    id="purchasePrice" 
                    type="number" 
                    {...register('purchasePrice', { valueAsNumber: true })} 
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="supplier">供应商</Label>
                  <Input id="supplier" {...register('supplier')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="invoiceNumber">发票号码</Label>
                  <Input id="invoiceNumber" {...register('invoiceNumber')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="invoiceUpload">购机发票</Label>
                  <div className="flex items-center gap-2">
                    <Input
                      id="invoiceUpload"
                      type="file"
                      accept="image/*,application/pdf"
                      onChange={handleFileUpload}
                      className="hidden"
                    />
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => document.getElementById('invoiceUpload')?.click()}
                    >
                      <Upload className="w-4 h-4 mr-2" />
                      上传发票
                    </Button>
                    {invoiceFile && (
                      <div className="flex items-center gap-2">
                        <span className="text-sm text-muted-foreground">已上传</span>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => setInvoiceFile(undefined)}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </TabsContent>

            {/* 保险信息 */}
            <TabsContent value="insurance" className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="insuranceCompany">保险公司</Label>
                  <Input id="insuranceCompany" {...register('insuranceCompany')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="insurancePolicyNumber">保单号</Label>
                  <Input id="insurancePolicyNumber" {...register('insurancePolicyNumber')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="insuranceStartDate">保险起始日期</Label>
                  <Input id="insuranceStartDate" type="date" {...register('insuranceStartDate')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="insuranceEndDate">保险结束日期</Label>
                  <Input id="insuranceEndDate" type="date" {...register('insuranceEndDate')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="insuranceAmount">保险金额 (元)</Label>
                  <Input 
                    id="insuranceAmount" 
                    type="number" 
                    {...register('insuranceAmount', { valueAsNumber: true })} 
                  />
                </div>
              </div>
            </TabsContent>
          </Tabs>

          <DialogFooter className="mt-6">
            <Button type="button" variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button type="submit">
              保存
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
