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 } from '@/server/modules/areas/area.schema';
import type { CreateAreaInput, UpdateAreaInput } from '@/server/modules/areas/area.schema';
import { AreaLevel } from '@/server/modules/areas/area.entity';
import { DisabledStatus } from '@/share/types';
import { AreaSelect } from './AreaSelect';

interface AreaFormProps {
  area?: UpdateAreaInput & { id?: number };
  onSubmit: (data: CreateAreaInput | UpdateAreaInput) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
}

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

  const form = useForm<CreateAreaInput | UpdateAreaInput>({
    resolver: zodResolver(isEditing ? updateAreaSchema : createAreaSchema),
    defaultValues: area ? {
      parentId: area.parentId,
      name: area.name,
      level: area.level,
      code: area.code,
      isDisabled: area.isDisabled,
    } : {
      parentId: 0,
      name: '',
      level: 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>
                <Select onValueChange={(value) => field.onChange(Number(value))} defaultValue={field.value?.toString()}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="选择层级" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value={AreaLevel.PROVINCE.toString()}>
                      省/直辖市
                    </SelectItem>
                    <SelectItem value={AreaLevel.CITY.toString()}>
                      市
                    </SelectItem>
                    <SelectItem value={AreaLevel.DISTRICT.toString()}>
                      区/县
                    </SelectItem>
                  </SelectContent>
                </Select>
                <FormDescription>
                  选择省市区层级
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 父级区域选择 */}
          <FormField
            control={form.control}
            name="parentId"
            render={({ field }) => {
              const level = form.watch('level');
              const showParentSelect = level !== AreaLevel.PROVINCE;

              return (
                <FormItem>
                  <FormLabel>父级区域</FormLabel>
                  {showParentSelect ? (
                    <>
                      <FormControl>
                        <AreaSelect
                          value={{
                            districtId: level === AreaLevel.DISTRICT ? field.value || undefined : undefined
                          }}
                          onChange={(value) => {
                            // 根据层级设置父级ID
                            if (level === AreaLevel.CITY) {
                              field.onChange(value.provinceId || 0);
                            } else if (level === AreaLevel.DISTRICT) {
                              field.onChange(value.cityId || 0);
                            }
                          }}
                          required
                        />
                      </FormControl>
                      <FormDescription>
                        {level === AreaLevel.CITY
                          ? '选择所属省份'
                          : '选择所属城市'}
                      </FormDescription>
                    </>
                  ) : (
                    <>
                      <FormControl>
                        <Input
                          type="number"
                          value={0}
                          disabled
                          className="bg-muted"
                        />
                      </FormControl>
                      <FormDescription>
                        省/直辖市没有父级区域
                      </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>
  );
};