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 { Calendar } from 'lucide-react';
import { format } from 'date-fns';
import { createActivitySchema, updateActivitySchema } from '@d8d/server/modules/activities/activity.schema';
import type { CreateActivityInput, UpdateActivityInput } from '@d8d/server/modules/activities/activity.schema';
import { ActivityType } from '@d8d/server/modules/activities/activity.entity';
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 ActivityFormProps {
  initialData?: UpdateActivityInput & { id?: number };
  onSubmit: (data: CreateActivityInput | UpdateActivityInput) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
}


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

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

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

    return submitData;
  };

  const form = useForm({
    resolver: zodResolver(isEditing ? updateActivitySchema : createActivitySchema),
    defaultValues: initialData ? {
      name: initialData.name || '',
      description: initialData.description || '',
      type: initialData.type || ActivityType.DEPARTURE,
      startDate: initialData.startDate ? formatDateTimeForInput(initialData.startDate) : '',
      endDate: initialData.endDate ? formatDateTimeForInput(initialData.endDate) : '',
      venueLocationId: initialData.venueLocationId,
      isDisabled: initialData.isDisabled
    } : {
      name: '',
      description: '',
      type: ActivityType.DEPARTURE,
      startDate: '',
      endDate: '',
      venueLocationId: undefined,
    }
  });

  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="请输入活动名称"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  活动的显示名称，最多255个字符
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 活动类型 */}
          <FormField
            control={form.control}
            name="type"
            render={({ field }) => (
              <FormItem>
                <FormLabel>活动类型 *</FormLabel>
                <Select onValueChange={field.onChange} defaultValue={field.value}>
                  <FormControl>
                    <SelectTrigger data-testid="activity-type-select">
                      <SelectValue placeholder="选择活动类型" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value={ActivityType.DEPARTURE}>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-blue-500" />
                        <span>去程活动</span>
                      </div>
                    </SelectItem>
                    <SelectItem value={ActivityType.RETURN}>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-green-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>
          )}
        />

        {/* 举办地点 */}
        <FormField
          control={form.control}
          name="venueLocationId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>举办地点 *</FormLabel>
              <FormControl>
                <LocationSelect
                  placeholder="请选择举办地点"
                  value={field.value}
                  onValueChange={field.onChange}
                  data-testid="venue-location-select"
                />
              </FormControl>
              <FormDescription>
                活动举办的具体地点
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 开始日期 */}
          <FormField
            control={form.control}
            name="startDate"
            render={({ field }) => (
              <FormItem>
                <FormLabel>开始日期 *</FormLabel>
                <FormControl>
                  <Input
                    type="datetime-local"
                    value={field.value as string}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    ref={field.ref}
                  />
                </FormControl>
                <FormDescription>
                  活动的开始时间
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 结束日期 */}
          <FormField
            control={form.control}
            name="endDate"
            render={({ field }) => (
              <FormItem>
                <FormLabel>结束日期 *</FormLabel>
                <FormControl>
                  <Input
                    type="datetime-local"
                    value={field.value as string}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    ref={field.ref}
                  />
                </FormControl>
                <FormDescription>
                  活动的结束时间
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* 状态选择（仅在编辑时显示） */}
        {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>
  );
};