import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
import { createAreaSchema, updateAreaSchema, AreaLevel } from '@d8d/geo-areas/schemas';
import type { CreateAreaInput, UpdateAreaInput } from '@d8d/geo-areas/schemas';
import { DisabledStatus } from '@/share/types';

interface AreaFormProps {
  area?: UpdateAreaInput & { id?: number };
  onSubmit: (data: CreateAreaInput | UpdateAreaInput) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
  /** 智能预填的层级 */
  smartLevel?: number;
  /** 智能预填的父级ID */
  smartParentId?: number;
}

// 辅助函数：根据层级值获取显示名称
const getLevelDisplayName = (level: number | undefined): string => {
  switch (level) {
    case AreaLevel.PROVINCE:
      return '省/直辖市';
    case AreaLevel.CITY:
      return '市';
    case AreaLevel.DISTRICT:
      return '区/县';
    default:
      return '未知层级';
  }
};

export const AreaForm: React.FC<AreaFormProps> = ({
  area,
  onSubmit,
  onCancel,
  isLoading = false,
  smartLevel,
  smartParentId
}) => {
  const isEditing = !!area;

  const form = useForm<CreateAreaInput | UpdateAreaInput>({
    resolver: zodResolver(isEditing ? updateAreaSchema : createAreaSchema),
    defaultValues: area ? {
      parentId: area.parentId || undefined,
      name: area.name,
      level: area.level,
      code: area.code,
      isDisabled: area.isDisabled,
    } : {
      parentId: smartParentId || undefined,
      name: '',
      level: smartLevel ?? AreaLevel.PROVINCE,
      code: '',
      isDisabled: DisabledStatus.ENABLED,
    },
  });

  const handleSubmit = async (data: CreateAreaInput | UpdateAreaInput) => {
    await onSubmit(data);
  };


  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
        <div className="grid grid-cols-1 gap-6">
          {/* 层级显示（只读） */}
          <FormField
            control={form.control}
            name="level"
            render={({ field }) => (
              <FormItem>
                <FormLabel>层级</FormLabel>
                <FormControl>
                  <Input
                    value={getLevelDisplayName(field.value)}
                    disabled
                    className="bg-muted"
                  />
                </FormControl>
                <FormDescription>
                  根据操作上下文自动设置的层级
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 父级区域显示（只读） */}
          <FormField
            control={form.control}
            name="parentId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>父级区域</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    value={field.value || ''}
                    disabled
                    className="bg-muted"
                    placeholder="顶级区域（无父级）"
                  />
                </FormControl>
                <FormDescription>
                  根据操作上下文自动设置的父级区域ID
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 区域名称 */}
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>区域名称</FormLabel>
                <FormControl>
                  <Input
                    placeholder="输入区域名称"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  输入省市区名称，如：北京市、上海市、朝阳区等
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 行政区划代码 */}
          <FormField
            control={form.control}
            name="code"
            render={({ field }) => (
              <FormItem>
                <FormLabel>行政区划代码</FormLabel>
                <FormControl>
                  <Input
                    placeholder="输入行政区划代码"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  输入标准的行政区划代码
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 状态选择 */}
          <FormField
            control={form.control}
            name="isDisabled"
            render={({ field }) => (
              <FormItem>
                <FormLabel>状态</FormLabel>
                <Select onValueChange={(value) => field.onChange(Number(value))} defaultValue={field.value?.toString()}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value={DisabledStatus.ENABLED.toString()}>
                      启用
                    </SelectItem>
                    <SelectItem value={DisabledStatus.DISABLED.toString()}>
                      禁用
                    </SelectItem>
                  </SelectContent>
                </Select>
                <FormDescription>
                  选择省市区状态
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* 表单操作按钮 */}
        <div className="flex justify-end gap-4">
          <Button
            type="button"
            variant="outline"
            onClick={onCancel}
            disabled={isLoading}
          >
            取消
          </Button>
          <Button
            type="submit"
            disabled={isLoading}
          >
            {isLoading ? '提交中...' : isEditing ? '更新' : '创建'}
          </Button>
        </div>
      </form>
    </Form>
  );
};