/**
 * filekorolheader: 添加/编辑设备类型对话框 - 设备类型信息录入组件
 * 功能：新增设备类型、编辑设备类型信息、表单验证
 * 路径：/ai-crop-model/data-sense-center/device-type/components
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */

import React from 'react';
import { useForm } from 'react-hook-form';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { DeviceType, DeviceTypeAction } from './deviceTypeReducer';

interface AddDeviceTypeDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingType: DeviceType | null;
  dispatch: React.Dispatch<DeviceTypeAction>;
}

export function AddDeviceTypeDialog({ open, onOpenChange, editingType, dispatch }: AddDeviceTypeDialogProps) {
  const { register, handleSubmit, setValue, reset, formState: { errors } } = useForm();

  // 当编辑类型变化时，填充表单
  React.useEffect(() => {
    if (editingType) {
      setValue('name', editingType.name);
      setValue('manufacturer', editingType.manufacturer || '');
      setValue('model', editingType.model || '');
      setValue('description', editingType.description || '');
    } else {
      reset();
    }
  }, [editingType, setValue, reset]);

  const onSubmit = (data: any) => {
    if (editingType) {
      const updated: DeviceType = {
        ...editingType,
        ...data,
        updatedAt: new Date().toISOString(),
      };
      dispatch({ type: 'UPDATE_DEVICE_TYPE', payload: updated });
    } else {
      const newType: DeviceType = {
        id: `device-type-${Date.now()}`,
        ...data,
        parameterDefinitions: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      dispatch({ type: 'ADD_DEVICE_TYPE', payload: newType });
    }

    reset();
  };

  const handleOpenChange = (open: boolean) => {
    if (!open) {
      reset();
    }
    onOpenChange(open);
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{editingType ? '编辑设备类型' : '新增设备类型'}</DialogTitle>
          <DialogDescription>
            填写设备类型的基本信息
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} 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: '请输入类型名称' })}
                placeholder="例如：土壤传感器"
              />
              {errors.name && (
                <p className="text-sm text-destructive">{errors.name.message as string}</p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="manufacturer">品牌</Label>
              <Input
                id="manufacturer"
                {...register('manufacturer')}
                placeholder="例如：施耐德"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="model">型号</Label>
              <Input
                id="model"
                {...register('model')}
                placeholder="例如：SOIL-100"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">描述</Label>
            <Textarea
              id="description"
              {...register('description')}
              placeholder="设备类型的详细描述..."
              rows={3}
            />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
              取消
            </Button>
            <Button type="submit">
              {editingType ? '保存' : '添加'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}