"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";

interface TournamentFormData {
  name: string;
  description: string;
  date: string;
  endDate: string;
  type: string;
  category: string;
  maxTeams: number;
  price: number;
  siteId: string;
}

interface Site {
  id: string;
  name: string;
}

interface TournamentFormProps {
  initialData?: Partial<TournamentFormData>;
  onSubmit: (data: TournamentFormData) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
  mode?: "create" | "edit";
}

const tournamentTypes = [
  { value: "SINGLE_ELIMINATION", label: "Eliminacion Directa" },
  { value: "DOUBLE_ELIMINATION", label: "Doble Eliminacion" },
  { value: "ROUND_ROBIN", label: "Round Robin" },
  { value: "LEAGUE", label: "Liga" },
];

const categories = [
  { value: "", label: "Sin categoria" },
  { value: "1ra", label: "1ra Categoria" },
  { value: "2da", label: "2da Categoria" },
  { value: "3ra", label: "3ra Categoria" },
  { value: "4ta", label: "4ta Categoria" },
  { value: "5ta", label: "5ta Categoria" },
  { value: "Mixto", label: "Mixto" },
  { value: "Femenil", label: "Femenil" },
  { value: "Varonil", label: "Varonil" },
  { value: "Open", label: "Open" },
];

export function TournamentForm({
  initialData,
  onSubmit,
  onCancel,
  isLoading = false,
  mode = "create",
}: TournamentFormProps) {
  const [sites, setSites] = useState<Site[]>([]);
  const [loadingSites, setLoadingSites] = useState(true);
  const [formData, setFormData] = useState<TournamentFormData>({
    name: initialData?.name || "",
    description: initialData?.description || "",
    date: initialData?.date || "",
    endDate: initialData?.endDate || "",
    type: initialData?.type || "SINGLE_ELIMINATION",
    category: initialData?.category || "",
    maxTeams: initialData?.maxTeams || 16,
    price: initialData?.price || 0,
    siteId: initialData?.siteId || "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Fetch sites
  useEffect(() => {
    async function fetchSites() {
      try {
        const response = await fetch("/api/sites");
        if (response.ok) {
          const data = await response.json();
          setSites(data);
          // Set default site if not set
          if (!formData.siteId && data.length > 0) {
            setFormData(prev => ({ ...prev, siteId: data[0].id }));
          }
        }
      } catch (error) {
        console.error("Error fetching sites:", error);
      } finally {
        setLoadingSites(false);
      }
    }
    fetchSites();
  }, []);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "number" ? parseFloat(value) || 0 : value,
    }));
    // Clear error when field is modified
    if (errors[name]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "El nombre es requerido";
    }
    if (!formData.date) {
      newErrors.date = "La fecha de inicio es requerida";
    }
    if (!formData.siteId) {
      newErrors.siteId = "Selecciona una sede";
    }
    if (formData.maxTeams < 2) {
      newErrors.maxTeams = "Minimo 2 equipos";
    }
    if (formData.price < 0) {
      newErrors.price = "El precio no puede ser negativo";
    }
    if (formData.endDate && new Date(formData.endDate) < new Date(formData.date)) {
      newErrors.endDate = "La fecha de fin debe ser posterior a la de inicio";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    await onSubmit(formData);
  };

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <form onSubmit={handleSubmit}>
        <CardHeader>
          <CardTitle>
            {mode === "create" ? "Nuevo Torneo" : "Editar Torneo"}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Name */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">
              Nombre del Torneo *
            </label>
            <Input
              name="name"
              value={formData.name}
              onChange={handleChange}
              placeholder="Ej: Torneo Navidad 2024"
              className={errors.name ? "border-red-500" : ""}
            />
            {errors.name && (
              <p className="text-red-500 text-xs mt-1">{errors.name}</p>
            )}
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">
              Descripcion
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleChange}
              placeholder="Descripcion del torneo..."
              rows={3}
              className="flex w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-primary-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
            />
          </div>

          {/* Site Selection */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">
              Sede *
            </label>
            <select
              name="siteId"
              value={formData.siteId}
              onChange={handleChange}
              className="flex h-10 w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
              disabled={loadingSites}
            >
              <option value="">Selecciona una sede</option>
              {sites.map((site) => (
                <option key={site.id} value={site.id}>
                  {site.name}
                </option>
              ))}
            </select>
            {errors.siteId && (
              <p className="text-red-500 text-xs mt-1">{errors.siteId}</p>
            )}
          </div>

          {/* Dates */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Fecha de Inicio *
              </label>
              <Input
                type="datetime-local"
                name="date"
                value={formData.date}
                onChange={handleChange}
                className={errors.date ? "border-red-500" : ""}
              />
              {errors.date && (
                <p className="text-red-500 text-xs mt-1">{errors.date}</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Fecha de Fin
              </label>
              <Input
                type="datetime-local"
                name="endDate"
                value={formData.endDate}
                onChange={handleChange}
                className={errors.endDate ? "border-red-500" : ""}
              />
              {errors.endDate && (
                <p className="text-red-500 text-xs mt-1">{errors.endDate}</p>
              )}
            </div>
          </div>

          {/* Type and Category */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Tipo de Torneo
              </label>
              <select
                name="type"
                value={formData.type}
                onChange={handleChange}
                className="flex h-10 w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
              >
                {tournamentTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Categoria
              </label>
              <select
                name="category"
                value={formData.category}
                onChange={handleChange}
                className="flex h-10 w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
              >
                {categories.map((cat) => (
                  <option key={cat.value} value={cat.value}>
                    {cat.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Max Teams and Price */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Maximo de Equipos *
              </label>
              <Input
                type="number"
                name="maxTeams"
                value={formData.maxTeams}
                onChange={handleChange}
                min={2}
                max={128}
                className={errors.maxTeams ? "border-red-500" : ""}
              />
              {errors.maxTeams && (
                <p className="text-red-500 text-xs mt-1">{errors.maxTeams}</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Precio de Inscripcion
              </label>
              <Input
                type="number"
                name="price"
                value={formData.price}
                onChange={handleChange}
                min={0}
                step={50}
                className={errors.price ? "border-red-500" : ""}
              />
              {errors.price && (
                <p className="text-red-500 text-xs mt-1">{errors.price}</p>
              )}
            </div>
          </div>
        </CardContent>
        <CardFooter className="flex justify-end gap-3 border-t border-primary-200 bg-primary-50 pt-4">
          <Button type="button" variant="outline" onClick={onCancel}>
            Cancelar
          </Button>
          <Button type="submit" disabled={isLoading}>
            {isLoading ? (
              <span className="flex items-center gap-2">
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                Guardando...
              </span>
            ) : mode === "create" ? (
              "Crear Torneo"
            ) : (
              "Guardar Cambios"
            )}
          </Button>
        </CardFooter>
      </form>
    </Card>
  );
}
