import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { insertTeamSchema, type Team } from "@shared/schema";
import { z } from "zod";

const teamFormSchema = insertTeamSchema.extend({
  logoFile: z.any().optional(),
  organizationId: z.number().optional(), // Make organizationId optional in form
});

type TeamFormData = z.infer<typeof teamFormSchema>;

interface TeamFormProps {
  team?: Team;
  onSuccess: () => void;
}

export default function TeamForm({ team, onSuccess }: TeamFormProps) {
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const form = useForm<TeamFormData>({
    resolver: zodResolver(teamFormSchema),
    defaultValues: {
      name: team?.name || "",
      sport: team?.sport || "",
      status: team?.status || "active",
      description: team?.description || "",
    },
  });

  // Reset form when team prop changes
  useEffect(() => {
    if (team) {
      form.reset({
        name: team.name || "",
        sport: team.sport || "",
        status: team.status || "active",
        description: team.description || "",
      });
    }
  }, [team, form]);

  const mutation = useMutation({
    mutationFn: async (data: TeamFormData) => {
      console.log("Mutation started with data:", data);
      
      const formData = new FormData();
      formData.append("name", data.name || "");
      formData.append("sport", data.sport || "");
      formData.append("status", data.status || "active");
      formData.append("organizationId", "1"); // Default organization ID
      if (data.description) formData.append("description", data.description);
      if (logoFile) formData.append("logo", logoFile);

      const url = team ? `/api/teams/${team.id}` : "/api/teams";
      const method = team ? "PUT" : "POST";
      
      console.log("Making request to:", url, "with method:", method);
      console.log("FormData contents:", {
        name: data.name,
        sport: data.sport,
        status: data.status,
        description: data.description,
        hasLogo: !!logoFile
      });

      const response = await fetch(url, {
        method,
        body: formData,
        credentials: "include",
      });

      console.log("Response status:", response.status);
      console.log("Response ok:", response.ok);

      if (!response.ok) {
        const error = await response.json();
        console.error("Request failed with error:", error);
        throw new Error(error.message || "Failed to save team");
      }

      const result = await response.json();
      console.log("Request successful, result:", result);
      return result;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/teams"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
      toast({
        title: "Success",
        description: `Team ${team ? "updated" : "created"} successfully`,
      });
      onSuccess();
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || `Failed to ${team ? "update" : "create"} team`,
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: TeamFormData) => {
    console.log("Form submitted with data:", data);
    console.log("Form errors:", form.formState.errors);
    console.log("Form is valid:", form.formState.isValid);
    
    if (!data.name || !data.sport) {
      console.error("Missing required fields:", { name: data.name, sport: data.sport });
      toast({
        title: "Validation Error",
        description: "Please fill in all required fields (name and sport)",
        variant: "destructive",
      });
      return;
    }
    
    console.log("Triggering mutation with data:", data);
    mutation.mutate(data);
  };

  return (
    <Form {...form}>
      <form onSubmit={(e) => {
        console.log("Form onSubmit triggered");
        console.log("Form errors:", form.formState.errors);
        console.log("Form is valid:", form.formState.isValid);
        console.log("Form dirty fields:", form.formState.dirtyFields);
        e.preventDefault();
        form.handleSubmit(onSubmit, (errors) => {
          console.log("Form validation failed:", errors);
        })(e);
      }} 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>Team Name</FormLabel>
                <FormControl>
                  <Input placeholder="Enter team name" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="sport"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Sport</FormLabel>
                <FormControl>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select sport" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="football">Football</SelectItem>
                      <SelectItem value="basketball">Basketball</SelectItem>
                      <SelectItem value="baseball">Baseball</SelectItem>
                      <SelectItem value="soccer">Soccer</SelectItem>
                      <SelectItem value="tennis">Tennis</SelectItem>
                      <SelectItem value="swimming">Swimming</SelectItem>
                      <SelectItem value="track">Track & Field</SelectItem>
                      <SelectItem value="volleyball">Volleyball</SelectItem>
                      <SelectItem value="hockey">Hockey</SelectItem>
                      <SelectItem value="rugby">Rugby</SelectItem>
                      <SelectItem value="other">Other</SelectItem>
                    </SelectContent>
                  </Select>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <FormField
          control={form.control}
          name="status"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Status</FormLabel>
              <FormControl>
                <Select onValueChange={field.onChange} defaultValue={field.value}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Active</SelectItem>
                    <SelectItem value="inactive">Inactive</SelectItem>
                  </SelectContent>
                </Select>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Description</FormLabel>
              <FormControl>
                <Textarea 
                  placeholder="Enter team description (optional)"
                  className="min-h-[100px]"
                  value={field.value || ""}
                  onChange={field.onChange}
                  onBlur={field.onBlur}
                  name={field.name}
                  ref={field.ref}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="space-y-2">
          <label className="text-sm font-medium">Team Logo</label>
          <Input
            type="file"
            accept="image/*"
            onChange={(e) => setLogoFile(e.target.files?.[0] || null)}
            className="cursor-pointer"
          />
          <p className="text-xs text-gray-500">
            Upload a team logo (optional). Supported formats: JPEG, PNG, GIF. Max size: 5MB.
          </p>
        </div>

        <div className="flex justify-end space-x-4">
          <Button type="button" variant="outline" onClick={onSuccess}>
            Cancel
          </Button>
          <Button 
            type="submit" 
            disabled={mutation.isPending}
          >
            {mutation.isPending ? "Saving..." : team ? "Update Team" : "Create Team"}
          </Button>
        </div>
      </form>
    </Form>
  );
}
