import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { createAreaSchemaMt, updateAreaSchemaMt, AreaLevel } from '@d8d/geo-areas-mt/schemas';
import type { CreateAreaInputMt, UpdateAreaInputMt } from '@d8d/geo-areas-mt/schemas';

// 禁用状态枚举
enum DisabledStatus {
  ENABLED = 0,
  DISABLED = 1
}

interface AreaFormProps {
  area?: UpdateAreaInputMt & { id?: number };
  onSubmit: (data: CreateAreaInputMt | UpdateAreaInputMt) => 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 '区/县';
    case AreaLevel.TOWN:
      return '街道/乡镇';
    default:
      return '未知层级';
  }
};

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

  const form = useForm<CreateAreaInputMt | UpdateAreaInputMt>({
    resolver: zodResolver(isEditing ? updateAreaSchemaMt : createAreaSchemaMt),
    defaultValues: area ? {
      tenantId: area.tenantId,
      parentId: area.parentId,
      name: area.name,
      level: area.level,
      code: area.code,
      isDisabled: area.isDisabled,
    } : {
      tenantId: 1, // 测试环境使用默认tenantId
      parentId: smartParentId || null,
      name: '',
      level: smartLevel ?? AreaLevel.PROVINCE,
      code: '',
      isDisabled: DisabledStatus.ENABLED,
    },
  });

  const handleSubmit = async (data: CreateAreaInputMt | UpdateAreaInputMt) => {
    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>
  );
};