import { useState } 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 { 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 { insertCoachSchema, type Coach } from "@shared/schema";
import { z } from "zod";

const coachFormSchema = insertCoachSchema.extend({
  profileImageFile: z.any().optional(),
});

type CoachFormData = z.infer<typeof coachFormSchema>;

interface CoachFormProps {
  coach?: Coach;
  onSuccess: () => void;
}

export default function CoachForm({ coach, onSuccess }: CoachFormProps) {
  const [profileImageFile, setProfileImageFile] = useState<File | null>(null);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const form = useForm<CoachFormData>({
    resolver: zodResolver(coachFormSchema),
    defaultValues: {
      firstName: coach?.firstName || "",
      lastName: coach?.lastName || "",
      email: coach?.email || "",
      phone: coach?.phone || "",
      experience: coach?.experience || undefined,
      specialization: coach?.specialization || "",
      status: coach?.status || "active",
    },
  });

  const mutation = useMutation({
    mutationFn: async (data: CoachFormData) => {
      console.log("Coach form submitted with data:", data);
      const formData = new FormData();
      formData.append("firstName", data.firstName);
      formData.append("lastName", data.lastName);
      formData.append("email", data.email);
      if (data.phone) formData.append("phone", data.phone);
      if (data.experience !== undefined && data.experience !== null) formData.append("experience", data.experience.toString());
      if (data.specialization) formData.append("specialization", data.specialization);
      formData.append("organizationId", "1"); // Default organization ID
      formData.append("status", data.status);
      if (profileImageFile) formData.append("profileImage", profileImageFile);

      const url = coach ? `/api/coaches/${coach.id}` : "/api/coaches";
      const method = coach ? "PUT" : "POST";

      console.log("Making coach request to:", url, "with method:", method);
      const response = await fetch(url, {
        method,
        body: formData,
        credentials: "include",
      });

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

      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/coaches"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
      toast({
        title: "Success",
        description: `Coach ${coach ? "updated" : "created"} successfully`,
      });
      onSuccess();
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || `Failed to ${coach ? "update" : "create"} coach`,
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: CoachFormData) => {
    mutation.mutate(data);
  };

  return (
    <div className="w-full p-4">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {/* Personal Information */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Personal Information</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="firstName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>First Name</FormLabel>
                    <FormControl>
                      <Input placeholder="Enter first name" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

            <FormField
              control={form.control}
              name="lastName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Last Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter last name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input type="email" placeholder="Enter email address" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Phone (Optional)</FormLabel>
                  <FormControl>
                    <Input 
                      type="tel"
                      placeholder="Enter phone number" 
                      {...field}
                      value={field.value || ""}
                      onChange={(e) => {
                        // Allow only numbers, spaces, dashes, parentheses, and plus sign
                        const value = e.target.value.replace(/[^+\d\s\-\(\)]/g, '');
                        field.onChange(value);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>

          {/* Professional Information */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Professional Information</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="specialization"
                render={({ field }) => (
                <FormItem>
                  <FormLabel>Specialization (Optional)</FormLabel>
                  <FormControl>
                    <Select onValueChange={field.onChange} defaultValue={field.value || ""}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select specialization" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">No specialization</SelectItem>
                        <SelectItem value="head_coach">Head Coach</SelectItem>
                        <SelectItem value="assistant_coach">Assistant Coach</SelectItem>
                        <SelectItem value="defensive_coordinator">Defensive Coordinator</SelectItem>
                        <SelectItem value="offensive_coordinator">Offensive Coordinator</SelectItem>
                        <SelectItem value="strength_conditioning">Strength & Conditioning</SelectItem>
                        <SelectItem value="goalkeeping">Goalkeeping Coach</SelectItem>
                        <SelectItem value="technical_coach">Technical Coach</SelectItem>
                        <SelectItem value="youth_development">Youth Development</SelectItem>
                        <SelectItem value="mental_performance">Mental Performance</SelectItem>
                        <SelectItem value="nutrition">Nutrition Coach</SelectItem>
                        <SelectItem value="rehabilitation">Rehabilitation Coach</SelectItem>
                        <SelectItem value="analytics">Performance Analytics</SelectItem>
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="experience"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Years of Experience (Optional)</FormLabel>
                  <FormControl>
                    <Input 
                      type="number" 
                      placeholder="Enter years of experience" 
                      {...field} 
                      onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <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>
              )}
            />
          </div>
        </div>

          {/* Profile Image */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Profile Image</h3>
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700 dark:text-gray-300">Profile Image (Optional)</label>
              <Input
                type="file"
                accept="image/*"
                onChange={(e) => setProfileImageFile(e.target.files?.[0] || null)}
                className="cursor-pointer"
              />
              <p className="text-xs text-gray-500 dark:text-gray-400">
                Upload a profile image. Supported formats: JPEG, PNG, GIF. Max size: 5MB.
              </p>
            </div>
          </div>

          <div className="flex flex-col sm:flex-row justify-end space-y-2 sm:space-y-0 sm:space-x-4 pt-6 border-t border-gray-200 dark:border-gray-700">
            <Button type="button" variant="outline" onClick={onSuccess} className="w-full sm:w-auto">
              Cancel
            </Button>
            <Button type="submit" disabled={mutation.isPending} className="w-full sm:w-auto">
              {mutation.isPending ? "Saving..." : coach ? "Update Coach" : "Add Coach"}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
