import { useForm } from 'react-hook-form@7.55.0';
import { DriverRecord, DriverStatus, TrainingRecord, ViolationRecord } from '../../../types/driver';
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Upload } from 'lucide-react';
import { useState, useEffect } from 'react';
import { TrainingRecordManagement } from './TrainingRecordManagement';
import { ViolationRecordManagement } from './ViolationRecordManagement';

interface DriverFormProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: Partial<DriverRecord>) => void;
  initialData?: DriverRecord;
}

export function DriverForm({ open, onClose, onSave, initialData }: DriverFormProps) {
  const { register, handleSubmit, setValue, formState: { errors } } = useForm({
    defaultValues: initialData
  });

  const [licensePhotos, setLicensePhotos] = useState({
    front: initialData?.driverLicense.frontPhoto,
    back: initialData?.driverLicense.backPhoto,
  });

  const [trainingRecords, setTrainingRecords] = useState<TrainingRecord[]>(
    initialData?.trainingRecords || []
  );

  const [violationRecords, setViolationRecords] = useState<ViolationRecord[]>(
    initialData?.violationRecords || []
  );

  // 当 initialData 变化时，重置记录
  useEffect(() => {
    setTrainingRecords(initialData?.trainingRecords || []);
    setViolationRecords(initialData?.violationRecords || []);
    setLicensePhotos({
      front: initialData?.driverLicense.frontPhoto,
      back: initialData?.driverLicense.backPhoto,
    });
  }, [initialData]);

  const onSubmit = (data: any) => {
    onSave({
      ...data,
      driverLicense: {
        ...data.driverLicense,
        frontPhoto: licensePhotos.front,
        backPhoto: licensePhotos.back,
      },
      trainingRecords,
      violationRecords,
    });
  };

  const handleFileUpload = (type: 'front' | 'back', e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setLicensePhotos(prev => ({ ...prev, [type]: reader.result as string }));
      };
      reader.readAsDataURL(file);
    }
  };

  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-5">
              <TabsTrigger value="basic">基本信息</TabsTrigger>
              <TabsTrigger value="license">证件信息</TabsTrigger>
              <TabsTrigger value="work">工作信息</TabsTrigger>
              <TabsTrigger value="training">培训记录</TabsTrigger>
              <TabsTrigger value="violation">违规记录</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="gender">性别 *</Label>
                  <Select
                    defaultValue={initialData?.gender}
                    onValueChange={(value) => setValue('gender', value as any)}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="男">男</SelectItem>
                      <SelectItem value="女">女</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="birthDate">出生日期 *</Label>
                  <Input id="birthDate" type="date" {...register('birthDate', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone">联系电话 *</Label>
                  <Input id="phone" {...register('phone', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email">电子邮箱</Label>
                  <Input id="email" type="email" {...register('email')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="idCard">身份证号 *</Label>
                  <Input id="idCard" {...register('idCard', { required: true })} />
                </div>

                <div className="space-y-2 col-span-2">
                  <Label htmlFor="address">联系地址</Label>
                  <Input id="address" {...register('address')} />
                </div>
              </div>
            </TabsContent>

            <TabsContent value="license" className="space-y-4">
              <h4>驾驶证信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="licenseNumber">驾驶证号 *</Label>
                  <Input id="licenseNumber" {...register('driverLicense.licenseNumber', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="licenseType">准驾车型 *</Label>
                  <Input id="licenseType" {...register('driverLicense.licenseType', { required: true })} placeholder="如：C1, B2, A" />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="licenseIssueDate">发证日期 *</Label>
                  <Input id="licenseIssueDate" type="date" {...register('driverLicense.issueDate', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="licenseExpiryDate">有效期至 *</Label>
                  <Input id="licenseExpiryDate" type="date" {...register('driverLicense.expiryDate', { required: true })} />
                </div>

                <div className="space-y-2">
                  <Label>驾驶证正页</Label>
                  <div>
                    <Input
                      id="licenseFront"
                      type="file"
                      accept="image/*"
                      onChange={(e) => handleFileUpload('front', e)}
                      className="hidden"
                    />
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => document.getElementById('licenseFront')?.click()}
                    >
                      <Upload className="w-4 h-4 mr-2" />
                      {licensePhotos.front ? '重新上传' : '上传照片'}
                    </Button>
                    {licensePhotos.front && <span className="ml-2 text-sm text-success">已上传</span>}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>驾驶证副页</Label>
                  <div>
                    <Input
                      id="licenseBack"
                      type="file"
                      accept="image/*"
                      onChange={(e) => handleFileUpload('back', e)}
                      className="hidden"
                    />
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => document.getElementById('licenseBack')?.click()}
                    >
                      <Upload className="w-4 h-4 mr-2" />
                      {licensePhotos.back ? '重新上传' : '上传照片'}
                    </Button>
                    {licensePhotos.back && <span className="ml-2 text-sm text-success">已上传</span>}
                  </div>
                </div>
              </div>

              <h4 className="mt-6">从业资格证（选填）</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="qualCertNumber">证书编号</Label>
                  <Input id="qualCertNumber" {...register('qualification.certificateNumber')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="qualIssueDate">发证日期</Label>
                  <Input id="qualIssueDate" type="date" {...register('qualification.issueDate')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="qualExpiryDate">有效期至</Label>
                  <Input id="qualExpiryDate" type="date" {...register('qualification.expiryDate')} />
                </div>
              </div>
            </TabsContent>

            <TabsContent value="work" className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="status">在岗状态</Label>
                  <Select
                    defaultValue={initialData?.status || '在岗'}
                    onValueChange={(value) => setValue('status', value as DriverStatus)}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="在岗">在岗</SelectItem>
                      <SelectItem value="休假">休假</SelectItem>
                      <SelectItem value="离职">离职</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="department">所属部门</Label>
                  <Input id="department" {...register('department')} />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="entryDate">入职日期 *</Label>
                  <Input id="entryDate" type="date" {...register('entryDate', { required: true })} />
                </div>
              </div>
            </TabsContent>

            <TabsContent value="training" className="space-y-4">
              <TrainingRecordManagement
                driverId={initialData?.id || 'temp-driver'}
                records={trainingRecords}
                onUpdate={setTrainingRecords}
              />
            </TabsContent>

            <TabsContent value="violation" className="space-y-4">
              <ViolationRecordManagement
                driverId={initialData?.id || 'temp-driver'}
                records={violationRecords}
                onUpdate={setViolationRecords}
              />
            </TabsContent>
          </Tabs>

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