import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@edr/ui-common';
import { useWagonTypes } from '@/hooks/use-wagon-types';

const wagonSchema = z.object({
  wagonNumber: z.string().min(1, 'Required'),
  wagonTypeId: z.string().min(1, 'Required'),
  maxPayloadWeight: z.coerce.number().min(0),
});

type WagonFormValues = z.infer<typeof wagonSchema>;

interface WagonFormProps {
  initialValues?: Partial<WagonFormValues>;
  onSubmit: (values: WagonFormValues) => void;
}

export function WagonForm({ initialValues, onSubmit }: WagonFormProps) {
  const { data: wagonTypes, isLoading: loadingTypes } = useWagonTypes();
  
  const form = useForm<WagonFormValues>({
    resolver: zodResolver(wagonSchema),
    defaultValues: {
      wagonNumber: initialValues?.wagonNumber || '',
      wagonTypeId: initialValues?.wagonTypeId || '',
      maxPayloadWeight: initialValues?.maxPayloadWeight || 0,
    },
  });

  const selectedTypeId = form.watch('wagonTypeId');

  // Autofill maxPayloadWeight when type changes
  useEffect(() => {
    if (selectedTypeId && wagonTypes) {
      const type = wagonTypes.find((t) => t.id === selectedTypeId);
      if (type) {
        // Only autofill if it's a new selection and field is at default or empty
        const currentWeight = form.getValues('maxPayloadWeight');
        if (!initialValues?.wagonTypeId || selectedTypeId !== initialValues.wagonTypeId) {
            form.setValue('maxPayloadWeight', Number(type.capacityTons));
        }
      }
    }
  }, [selectedTypeId, wagonTypes, form, initialValues?.wagonTypeId]);

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="wagonNumber"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Wagon Number</FormLabel>
              <FormControl>
                <Input placeholder="e.g. W12345" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="wagonTypeId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Wagon Type</FormLabel>
              <Select onValueChange={field.onChange} defaultValue={field.value} disabled={loadingTypes}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select wagon type" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {wagonTypes?.map((type) => (
                    <SelectItem key={type.id} value={type.id}>
                      {type.code} - {type.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="maxPayloadWeight"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Max Payload Weight (Tons)</FormLabel>
              <FormControl>
                <Input type="number" step="0.001" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </form>
    </Form>
  );
}
