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 { Textarea } from '@/client/components/ui/textarea';
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 { MapPin, DollarSign, Users, Car } from 'lucide-react';
import { format } from 'date-fns';
import { createRouteSchema, updateRouteSchema, VehicleType } from '@/server/modules/routes/route.schema';
import type { CreateRouteInput, UpdateRouteInput } from '@/server/modules/routes/route.schema';
import { ActivitySelect } from './ActivitySelect';
import { LocationSelect } from './LocationSelect';

// 将Date对象格式化为 datetime-local 输入框需要的格式
const formatDateTimeForInput = (date: Date): string => {
  // 使用 date-fns 转换为 YYYY-MM-DDTHH:mm 格式
  return format(date, "yyyy-MM-dd'T'HH:mm");
};

// 将 datetime-local 输入框的值转换为Date对象
const parseDateTimeFromInput = (dateString: string): Date => {
  return new Date(dateString);
};

interface RouteFormProps {
  initialData?: UpdateRouteInput & { id?: number };
  onSubmit: (data: CreateRouteInput | UpdateRouteInput) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
}

export const RouteForm: React.FC<RouteFormProps> = ({
  initialData,
  onSubmit,
  onCancel,
  isLoading = false
}) => {
  const isEditing = !!initialData?.id;

  // 创建表单数据转换函数
  const transformFormDataToSubmit = (formData: any): CreateRouteInput | UpdateRouteInput => {
    const submitData: any = { ...formData };

    // 转换时间字段为Date对象
    if (formData.departureTime) {
      submitData.departureTime = parseDateTimeFromInput(formData.departureTime);
    }

    return submitData;
  };

  const form = useForm({
    resolver: zodResolver(isEditing ? updateRouteSchema : createRouteSchema),
    defaultValues: initialData ? {
      name: initialData.name || '',
      description: initialData.description || '',
      startLocationId: initialData.startLocationId || 0,
      endLocationId: initialData.endLocationId || 0,
      pickupPoint: initialData.pickupPoint || '',
      dropoffPoint: initialData.dropoffPoint || '',
      departureTime: initialData.departureTime ? formatDateTimeForInput(initialData.departureTime) : '',
      vehicleType: initialData.vehicleType as VehicleType || VehicleType.BUS,
      price: initialData.price || 0,
      seatCount: initialData.seatCount || 1,
      availableSeats: initialData.availableSeats || 1,
      activityId: initialData.activityId || 0,
      isDisabled: initialData.isDisabled
    } : {
      name: '',
      description: '',
      startLocationId: 0,
      endLocationId: 0,
      pickupPoint: '',
      dropoffPoint: '',
      departureTime: '',
      vehicleType: VehicleType.BUS,
      price: 0,
      seatCount: 1,
      availableSeats: 1,
      activityId: 0,
    }
  });

  const handleSubmit = async (formData: any) => {
    try {
      const submitData = transformFormDataToSubmit(formData);
      await onSubmit(submitData);
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 路线名称 */}
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>路线名称 *</FormLabel>
                <FormControl>
                  <Input
                    placeholder="请输入路线名称"
                    data-testid="route-name-input"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  路线的显示名称，最多255个字符
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 车型 */}
          <FormField
            control={form.control}
            name="vehicleType"
            render={({ field }) => (
              <FormItem>
                <FormLabel>车型 *</FormLabel>
                <Select onValueChange={field.onChange} defaultValue={field.value}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="选择车型" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value={VehicleType.BUS}>
                      <div className="flex items-center gap-2">
                        <Car className="h-4 w-4 text-blue-500" />
                        <span>大巴</span>
                      </div>
                    </SelectItem>
                    <SelectItem value={VehicleType.MINIBUS}>
                      <div className="flex items-center gap-2">
                        <Car className="h-4 w-4 text-green-500" />
                        <span>中巴</span>
                      </div>
                    </SelectItem>
                    <SelectItem value={VehicleType.CAR}>
                      <div className="flex items-center gap-2">
                        <Car className="h-4 w-4 text-orange-500" />
                        <span>小车</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
                <FormDescription>
                  选择路线的车型
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* 路线描述 */}
        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>路线描述</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="请输入路线描述（可选）"
                  className="min-h-[100px]"
                  {...field}
                  value={field.value || ''}
                />
              </FormControl>
              <FormDescription>
                路线的详细描述，最多1000个字符
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 出发地 */}
          <FormField
            control={form.control}
            name="startLocationId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>出发地 *</FormLabel>
                <FormControl>
                  <LocationSelect
                    placeholder="请选择出发地"
                    value={field.value}
                    onValueChange={field.onChange}
                    data-testid="start-location-select"
                  />
                </FormControl>
                <FormDescription>
                  路线的出发地点
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 目的地 */}
          <FormField
            control={form.control}
            name="endLocationId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>目的地 *</FormLabel>
                <FormControl>
                  <LocationSelect
                    placeholder="请选择目的地"
                    value={field.value}
                    onValueChange={field.onChange}
                    data-testid="end-location-select"
                  />
                </FormControl>
                <FormDescription>
                  路线的目的地
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 上车点 */}
          <FormField
            control={form.control}
            name="pickupPoint"
            render={({ field }) => (
              <FormItem>
                <FormLabel>上车点 *</FormLabel>
                <FormControl>
                  <div className="relative">
                    <MapPin className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="请输入上车点"
                      className="pl-8"
                      data-testid="pickup-point-input"
                      {...field}
                    />
                  </div>
                </FormControl>
                <FormDescription>
                  乘客上车的地点
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 下车点 */}
          <FormField
            control={form.control}
            name="dropoffPoint"
            render={({ field }) => (
              <FormItem>
                <FormLabel>下车点 *</FormLabel>
                <FormControl>
                  <div className="relative">
                    <MapPin className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="请输入下车点"
                      className="pl-8"
                      data-testid="dropoff-point-input"
                      {...field}
                    />
                  </div>
                </FormControl>
                <FormDescription>
                  乘客下车的地点
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 出发时间 */}
          <FormField
            control={form.control}
            name="departureTime"
            render={({ field }) => (
              <FormItem>
                <FormLabel>出发时间 *</FormLabel>
                <FormControl>
                  <Input
                    type="datetime-local"
                    data-testid="departure-time-input"
                    value={field.value as string}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    ref={field.ref}
                  />
                </FormControl>
                <FormDescription>
                  路线的出发时间
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 价格 */}
          <FormField
            control={form.control}
            name="price"
            render={({ field }) => (
              <FormItem>
                <FormLabel>价格 *</FormLabel>
                <FormControl>
                  <div className="relative">
                    <DollarSign className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      type="number"
                      step="0.01"
                      min="0"
                      placeholder="0.00"
                      className="pl-8"
                      data-testid="price-input"
                      {...field}
                      onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                    />
                  </div>
                </FormControl>
                <FormDescription>
                  路线的价格（元）
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 座位数 */}
          <FormField
            control={form.control}
            name="seatCount"
            render={({ field }) => (
              <FormItem>
                <FormLabel>总座位数 *</FormLabel>
                <FormControl>
                  <div className="relative">
                    <Users className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      type="number"
                      min="1"
                      max="1000"
                      placeholder="1"
                      className="pl-8"
                      data-testid="seat-count-input"
                      {...field}
                      onChange={(e) => field.onChange(parseInt(e.target.value) || 1)}
                    />
                  </div>
                </FormControl>
                <FormDescription>
                  车辆的总座位数
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 可用座位数 */}
          <FormField
            control={form.control}
            name="availableSeats"
            render={({ field }) => (
              <FormItem>
                <FormLabel>可用座位数 *</FormLabel>
                <FormControl>
                  <div className="relative">
                    <Users className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      type="number"
                      min="0"
                      max="1000"
                      placeholder="0"
                      className="pl-8"
                      data-testid="available-seats-input"
                      {...field}
                      onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                    />
                  </div>
                </FormControl>
                <FormDescription>
                  当前可用的座位数
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* 关联活动 */}
        <FormField
          control={form.control}
          name="activityId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>关联活动 *</FormLabel>
              <FormControl>
                <ActivitySelect
                  value={field.value}
                  onValueChange={field.onChange}
                  placeholder="请选择关联活动"
                  data-testid="activity-select"
                />
              </FormControl>
              <FormDescription>
                选择此路线关联的活动
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* 状态选择（仅在编辑时显示） */}
        {isEditing && (
          <FormField
            control={form.control}
            name="isDisabled"
            render={({ field }) => (
              <FormItem>
                <FormLabel>路线状态</FormLabel>
                <Select onValueChange={(value) => field.onChange(parseInt(value))} defaultValue={field.value?.toString()}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="选择路线状态" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="0">启用</SelectItem>
                    <SelectItem value="1">禁用</SelectItem>
                  </SelectContent>
                </Select>
                <FormDescription>
                  控制路线是否对用户可见
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        )}

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