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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { DialogFooter } from '@/client/components/ui/dialog';

// 表单验证Schema
const locationFormSchema = z.object({
  name: z.string().min(1, '地点名称不能为空').max(100, '地点名称不能超过100个字符'),
  address: z.string().min(1, '地址不能为空').max(200, '地址不能超过200个字符'),
  areaId: 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 Area {
  id: number;
  name: string;
  code: string;
}

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

/**
 * 地点表单组件
 */
export const LocationForm = ({
  onSubmit,
  isLoading = false,
  areas,
  initialData,
}: LocationFormProps) => {
  const form = useForm({
    resolver: zodResolver(locationFormSchema),
    defaultValues: initialData ? {
      name: initialData.name,
      address: initialData.address,
      areaId: initialData.area?.id || initialData.areaId,
      latitude: initialData.latitude || undefined,
      longitude: initialData.longitude || undefined,
    } : {
      name: '',
      address: '',
      areaId: undefined,
      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>
            )}
          />

          {/* 所属区域 */}
          <FormField
            control={form.control}
            name="areaId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>所属区域</FormLabel>
                <Select onValueChange={field.onChange} defaultValue={field.value?.toString()}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="请选择所属区域" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {areas.map((area) => (
                      <SelectItem key={area.id} value={area.id.toString()}>
                        {area.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FormDescription>
                  选择地点所属的省市区区域
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 坐标信息 */}
          <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>
  );
};