import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { insertJumpSchema } from "@shared/schema";
import { z } from "zod";
import { useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import type { Jump } from "@shared/schema";
import { format } from "date-fns";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { 
  Popover, 
  PopoverContent, 
  PopoverTrigger 
} from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { CalendarIcon } from "lucide-react";

// Extend the schema with additional validation
const extendedSchema = insertJumpSchema.extend({
  jumpNumber: z.number().positive("Jump number must be positive").int("Jump number must be an integer"),
  altitude: z.string().min(1, "Altitude is required"),
  jumpDate: z.date({
    required_error: "Jump date is required",
  }),
});

type FormValues = z.infer<typeof extendedSchema>;

interface AddJumpFormProps {
  editJump?: Jump;
  onSuccess?: () => void;
}

export default function AddJumpForm({ editJump, onSuccess }: AddJumpFormProps) {
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Jump types for the select dropdown
  const jumpTypes = [
    "Formation",
    "Freefly",
    "Angle",
    "Tracking",
    "Wingsuit",
    "AFF",
    "Tandem",
    "CRW",
    "Other"
  ];

  // Initialize the form with default values or edit values
  const form = useForm<FormValues>({
    resolver: zodResolver(extendedSchema),
    defaultValues: editJump ? {
      jumpNumber: editJump.jumpNumber,
      jumpType: editJump.jumpType,
      dropzone: editJump.dropzone,
      altitude: editJump.altitude,
      aircraft: editJump.aircraft,
      equipment: editJump.equipment,
      jumpDate: editJump.jumpDate ? new Date(editJump.jumpDate) : new Date(),
      notes: editJump.notes || "",
    } : {
      jumpNumber: 0,
      jumpType: "",
      dropzone: "",
      altitude: "",
      aircraft: "",
      equipment: "",
      jumpDate: new Date(),
      notes: "",
    },
  });

  // Create or update jump mutation
  const mutation = useMutation({
    mutationFn: async (values: FormValues) => {
      if (editJump) {
        // Update existing jump
        const response = await apiRequest('PATCH', `/api/jumps/${editJump.id}`, values);
        return response.json();
      } else {
        // Create new jump
        const response = await apiRequest('POST', '/api/jumps', values);
        return response.json();
      }
    },
    onSuccess: () => {
      toast({
        title: editJump ? "Jump Updated" : "Jump Added",
        description: editJump ? "Your jump has been updated successfully." : "Your new jump has been added to your logbook.",
      });
      
      // Reset form if it's a new jump
      if (!editJump) {
        form.reset({
          jumpNumber: 0,
          jumpType: "",
          dropzone: "",
          altitude: "",
          aircraft: "",
          equipment: "",
          jumpDate: new Date(),
          notes: "",
        });
      }
      
      // Invalidate queries to refresh data
      queryClient.invalidateQueries({ queryKey: ['/api/jumps'] });
      queryClient.invalidateQueries({ queryKey: ['/api/stats'] });
      
      // Call onSuccess callback if provided
      if (onSuccess) onSuccess();
      
      setIsSubmitting(false);
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: `Failed to ${editJump ? 'update' : 'add'} jump: ${error instanceof Error ? error.message : 'Unknown error'}`,
        variant: "destructive",
      });
      setIsSubmitting(false);
    }
  });

  // Form submission handler
  const onSubmit = (values: FormValues) => {
    setIsSubmitting(true);
    mutation.mutate(values);
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <FormField
            control={form.control}
            name="jumpNumber"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Jump Number *</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    placeholder="Enter jump number"
                    {...field}
                    onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="jumpType"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Type of Jump *</FormLabel>
                <Select 
                  onValueChange={field.onChange} 
                  defaultValue={field.value}
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Select jump type" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {jumpTypes.map((type) => (
                      <SelectItem key={type} value={type}>
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="dropzone"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Dropzone (DZ) *</FormLabel>
                <FormControl>
                  <Input placeholder="Enter dropzone name" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="altitude"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Altitude *</FormLabel>
                <FormControl>
                  <Input placeholder="e.g. 13,500 ft" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="aircraft"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Aircraft *</FormLabel>
                <FormControl>
                  <Input placeholder="e.g. Twin Otter" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="equipment"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Equipment *</FormLabel>
                <FormControl>
                  <Input placeholder="e.g. Javelin NJ" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="jumpDate"
            render={({ field }) => (
              <FormItem className="flex flex-col">
                <FormLabel>Jump Date *</FormLabel>
                <Popover>
                  <PopoverTrigger asChild>
                    <FormControl>
                      <Button
                        variant={"outline"}
                        className={`w-full pl-3 text-left font-normal ${!field.value ? "text-muted-foreground" : ""}`}
                      >
                        {field.value ? (
                          format(field.value, "PPP")
                        ) : (
                          <span>Pick a date</span>
                        )}
                        <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                      </Button>
                    </FormControl>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={field.value}
                      onSelect={field.onChange}
                      disabled={(date) =>
                        date > new Date() || date < new Date("1900-01-01")
                      }
                      initialFocus
                    />
                  </PopoverContent>
                </Popover>
                <FormMessage />
              </FormItem>
            )}
          />
          
          <FormField
            control={form.control}
            name="notes"
            render={({ field }) => (
              <FormItem className="md:col-span-2">
                <FormLabel>Notes</FormLabel>
                <FormControl>
                  <Textarea 
                    placeholder="Optional jump notes" 
                    className="resize-none" 
                    rows={3} 
                    value={field.value || ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    ref={field.ref}
                    name={field.name}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>
        
        <Button 
          type="submit" 
          className="bg-[#3B82F6] hover:bg-[#1E40AF] text-white"
          disabled={isSubmitting}
        >
          {isSubmitting ? "Saving..." : editJump ? "Update Jump" : "Save Jump"}
        </Button>
      </form>
    </Form>
  );
}
