import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/client/components/ui/button';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
import { Input } from '@/client/components/ui/input';
import { Textarea } from '@/client/components/ui/textarea';
import { DialogFooter } from '@/client/components/ui/dialog';
import { AreaSelect } from './AreaSelect';

// 表单验证Schema
const locationFormSchema = z.object({
  name: z.string().min(1, '地点名称不能为空').max(100, '地点名称不能超过100个字符'),
  address: z.string().min(1, '地址不能为空').max(200, '地址不能超过200个字符'),
  provinceId: z.coerce.number<number>().int().positive('请选择省份'),
  cityId: z.coerce.number<number>().int().positive('请选择城市'),
  districtId: z.coerce.number<number>().int().positive('请选择区县'),
  latitude: z.coerce.number<number>().optional(),
  longitude: z.coerce.number<number>().optional(),
});

type LocationFormValues = z.infer<typeof locationFormSchema>;

interface LocationFormProps {
  onSubmit: (data: LocationFormValues) => void;
  isLoading?: boolean;
  initialData?: any;
}

/**
 * 地点表单组件
 */
export const LocationForm = ({
  onSubmit,
  isLoading = false,
  initialData,
}: LocationFormProps) => {
  const form = useForm({
    resolver: zodResolver(locationFormSchema),
    defaultValues: initialData ? {
      name: initialData.name,
      address: initialData.address,
      provinceId: initialData.provinceId,
      cityId: initialData.cityId,
      districtId: initialData.districtId,
      latitude: initialData.latitude || undefined,
      longitude: initialData.longitude || undefined,
    } : {
      name: '',
      address: '',
      provinceId: 0,
      cityId: 0,
      districtId: 0,
      latitude: undefined,
      longitude: undefined,
    },
  });

  const handleSubmit = (data: LocationFormValues) => {
    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="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>地点名称</FormLabel>
                <FormControl>
                  <Input placeholder="请输入地点名称" {...field} />
                </FormControl>
                <FormDescription>
                  地点的显示名称，如"北京南站"、"上海虹桥站"等
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 地址 */}
          <FormField
            control={form.control}
            name="address"
            render={({ field }) => (
              <FormItem>
                <FormLabel>详细地址</FormLabel>
                <FormControl>
                  <Textarea
                    placeholder="请输入详细地址"
                    className="resize-none"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  地点的详细地址信息
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 省市区三级联动 */}
          <div className="col-span-full">
            <FormItem>
              <FormLabel>省市区选择</FormLabel>
              <FormControl>
                <AreaSelect
                  value={{
                    provinceId: form.watch('provinceId') === 0 ? undefined : form.watch('provinceId'),
                    cityId: form.watch('cityId') === 0 ? undefined : form.watch('cityId'),
                    districtId: form.watch('districtId') === 0 ? undefined : form.watch('districtId')
                  }}
                  onChange={(value) => {
                    form.setValue('provinceId', value.provinceId || 0);
                    form.setValue('cityId', value.cityId || 0);
                    form.setValue('districtId', value.districtId || 0);
                  }}
                  required={true}
                />
              </FormControl>
              <FormDescription>
                请选择地点所在的省份、城市和区县
              </FormDescription>
              <FormMessage />
            </FormItem>
          </div>

          {/* 坐标信息 */}
          <div className="grid grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="latitude"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>纬度</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="any"
                      placeholder="例如：39.9042"
                      {...field}
                      value={field.value === undefined || field.value === null ? '' : field.value}
                      onChange={(e) => {
                        const value = e.target.value === '' ? undefined : parseFloat(e.target.value);
                        field.onChange(value);
                      }}
                    />
                  </FormControl>
                  <FormDescription>
                    地点的纬度坐标（可选）
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="longitude"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>经度</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="any"
                      placeholder="例如：116.4074"
                      {...field}
                      value={field.value === undefined || field.value === null ? '' : field.value}
                      onChange={(e) => {
                        const value = e.target.value === '' ? undefined : parseFloat(e.target.value);
                        field.onChange(value);
                      }}
                    />
                  </FormControl>
                  <FormDescription>
                    地点的经度坐标（可选）
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>

        <DialogFooter>
          <Button type="submit" disabled={isLoading}>
            {isLoading ? '提交中...' : (initialData ? '更新地点' : '创建地点')}
          </Button>
        </DialogFooter>
      </form>
    </Form>
  );
};