"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Building2,
  MapPin,
  Users,
  Clock,
  DollarSign,
  Save,
  Plus,
  Pencil,
  Trash2,
  X,
} from "lucide-react";

interface Site {
  id: string;
  name: string;
  address: string;
  phone: string | null;
  openTime: string;
  closeTime: string;
  isActive: boolean;
}

interface Court {
  id: string;
  name: string;
  type: string;
  hourlyRate: number;
  peakHourlyRate: number | null;
  status: string;
  siteId: string;
  site?: { name: string };
}

interface User {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  role: string;
  isActive: boolean;
  site?: { name: string } | null;
}

export default function SettingsPage() {
  const [activeTab, setActiveTab] = useState("organization");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // Organization state
  const [orgName, setOrgName] = useState("SmashPoint Demo");
  const [orgEmail, setOrgEmail] = useState("info@smashpoint.com");
  const [orgPhone, setOrgPhone] = useState("+52 555 123 4567");
  const [currency, setCurrency] = useState("MXN");
  const [timezone, setTimezone] = useState("America/Mexico_City");

  // Sites state
  const [sites, setSites] = useState<Site[]>([]);
  const [loadingSites, setLoadingSites] = useState(true);
  const [editingSite, setEditingSite] = useState<Site | null>(null);
  const [showSiteForm, setShowSiteForm] = useState(false);

  // Courts state
  const [courts, setCourts] = useState<Court[]>([]);
  const [loadingCourts, setLoadingCourts] = useState(true);
  const [editingCourt, setEditingCourt] = useState<Court | null>(null);
  const [showCourtForm, setShowCourtForm] = useState(false);

  // Users state
  const [users, setUsers] = useState<User[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(true);

  useEffect(() => {
    fetchSites();
    fetchCourts();
    fetchUsers();
  }, []);

  const fetchSites = async () => {
    try {
      const res = await fetch("/api/sites");
      if (res.ok) {
        const data = await res.json();
        setSites(data.data || []);
      }
    } catch (error) {
      console.error("Error fetching sites:", error);
    } finally {
      setLoadingSites(false);
    }
  };

  const fetchCourts = async () => {
    try {
      const res = await fetch("/api/courts");
      if (res.ok) {
        const data = await res.json();
        setCourts(data.data || []);
      }
    } catch (error) {
      console.error("Error fetching courts:", error);
    } finally {
      setLoadingCourts(false);
    }
  };

  const fetchUsers = async () => {
    try {
      const res = await fetch("/api/users");
      if (res.ok) {
        const data = await res.json();
        setUsers(data.data || []);
      }
    } catch (error) {
      console.error("Error fetching users:", error);
    } finally {
      setLoadingUsers(false);
    }
  };

  const handleSaveOrganization = async () => {
    setLoading(true);
    // Simulate save
    await new Promise((resolve) => setTimeout(resolve, 500));
    setMessage({ type: "success", text: "Configuración guardada correctamente" });
    setLoading(false);
    setTimeout(() => setMessage(null), 3000);
  };

  const handleSaveSite = async (site: Partial<Site>) => {
    setLoading(true);
    try {
      const method = editingSite ? "PUT" : "POST";
      const url = editingSite ? `/api/sites/${editingSite.id}` : "/api/sites";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(site),
      });

      if (res.ok) {
        setMessage({ type: "success", text: editingSite ? "Sede actualizada" : "Sede creada" });
        fetchSites();
        setShowSiteForm(false);
        setEditingSite(null);
      } else {
        setMessage({ type: "error", text: "Error al guardar la sede" });
      }
    } catch (error) {
      setMessage({ type: "error", text: "Error de conexión" });
    } finally {
      setLoading(false);
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleSaveCourt = async (court: Partial<Court>) => {
    setLoading(true);
    try {
      const method = editingCourt ? "PUT" : "POST";
      const url = editingCourt ? `/api/courts/${editingCourt.id}` : "/api/courts";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(court),
      });

      if (res.ok) {
        setMessage({ type: "success", text: editingCourt ? "Cancha actualizada" : "Cancha creada" });
        fetchCourts();
        setShowCourtForm(false);
        setEditingCourt(null);
      } else {
        setMessage({ type: "error", text: "Error al guardar la cancha" });
      }
    } catch (error) {
      setMessage({ type: "error", text: "Error de conexión" });
    } finally {
      setLoading(false);
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleDeleteCourt = async (courtId: string) => {
    if (!confirm("¿Estás seguro de eliminar esta cancha?")) return;

    try {
      const res = await fetch(`/api/courts/${courtId}`, { method: "DELETE" });
      if (res.ok) {
        setMessage({ type: "success", text: "Cancha eliminada" });
        fetchCourts();
      } else {
        setMessage({ type: "error", text: "Error al eliminar la cancha" });
      }
    } catch (error) {
      setMessage({ type: "error", text: "Error de conexión" });
    }
    setTimeout(() => setMessage(null), 3000);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-primary-800">Configuración</h1>
        <p className="text-primary-600">Administra la configuración del sistema</p>
      </div>

      {/* Message */}
      {message && (
        <div
          className={`p-4 rounded-lg ${
            message.type === "success"
              ? "bg-accent/10 text-accent-700 border border-accent/20"
              : "bg-red-50 text-red-700 border border-red-200"
          }`}
        >
          {message.text}
        </div>
      )}

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4 lg:w-auto lg:inline-grid">
          <TabsTrigger value="organization" className="gap-2">
            <Building2 className="h-4 w-4" />
            <span className="hidden sm:inline">Organización</span>
          </TabsTrigger>
          <TabsTrigger value="sites" className="gap-2">
            <MapPin className="h-4 w-4" />
            <span className="hidden sm:inline">Sedes</span>
          </TabsTrigger>
          <TabsTrigger value="courts" className="gap-2">
            <Clock className="h-4 w-4" />
            <span className="hidden sm:inline">Canchas</span>
          </TabsTrigger>
          <TabsTrigger value="users" className="gap-2">
            <Users className="h-4 w-4" />
            <span className="hidden sm:inline">Usuarios</span>
          </TabsTrigger>
        </TabsList>

        {/* Organization Tab */}
        <TabsContent value="organization" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Información de la Organización</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Nombre de la organización
                  </label>
                  <Input
                    value={orgName}
                    onChange={(e) => setOrgName(e.target.value)}
                    placeholder="Nombre"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Email de contacto
                  </label>
                  <Input
                    type="email"
                    value={orgEmail}
                    onChange={(e) => setOrgEmail(e.target.value)}
                    placeholder="email@ejemplo.com"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Teléfono
                  </label>
                  <Input
                    value={orgPhone}
                    onChange={(e) => setOrgPhone(e.target.value)}
                    placeholder="+52 555 123 4567"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Moneda
                  </label>
                  <select
                    value={currency}
                    onChange={(e) => setCurrency(e.target.value)}
                    className="w-full rounded-lg border border-primary-200 bg-white px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                  >
                    <option value="MXN">MXN - Peso Mexicano</option>
                    <option value="USD">USD - Dólar</option>
                    <option value="EUR">EUR - Euro</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Zona horaria
                  </label>
                  <select
                    value={timezone}
                    onChange={(e) => setTimezone(e.target.value)}
                    className="w-full rounded-lg border border-primary-200 bg-white px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                  >
                    <option value="America/Mexico_City">Ciudad de México</option>
                    <option value="America/Monterrey">Monterrey</option>
                    <option value="America/Tijuana">Tijuana</option>
                    <option value="America/Cancun">Cancún</option>
                  </select>
                </div>
              </div>

              <div className="pt-4">
                <Button onClick={handleSaveOrganization} disabled={loading}>
                  <Save className="h-4 w-4 mr-2" />
                  {loading ? "Guardando..." : "Guardar cambios"}
                </Button>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Configuración de Reservas</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Duración por defecto (minutos)
                  </label>
                  <Input type="number" defaultValue={60} min={30} step={30} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Anticipación mínima (horas)
                  </label>
                  <Input type="number" defaultValue={2} min={0} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Anticipación máxima (días)
                  </label>
                  <Input type="number" defaultValue={14} min={1} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Horas para cancelar
                  </label>
                  <Input type="number" defaultValue={24} min={0} />
                </div>
              </div>

              <div className="pt-4">
                <Button onClick={handleSaveOrganization} disabled={loading}>
                  <Save className="h-4 w-4 mr-2" />
                  {loading ? "Guardando..." : "Guardar cambios"}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Sites Tab */}
        <TabsContent value="sites" className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-lg font-semibold text-primary-800">Sedes</h2>
            <Button onClick={() => { setEditingSite(null); setShowSiteForm(true); }}>
              <Plus className="h-4 w-4 mr-2" />
              Nueva Sede
            </Button>
          </div>

          {loadingSites ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {[1, 2, 3].map((i) => (
                <Card key={i} className="animate-pulse">
                  <CardContent className="p-6">
                    <div className="h-6 bg-primary-100 rounded w-3/4 mb-2" />
                    <div className="h-4 bg-primary-100 rounded w-full mb-2" />
                    <div className="h-4 bg-primary-100 rounded w-1/2" />
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {sites.map((site) => (
                <Card key={site.id} className="hover:shadow-md transition-shadow">
                  <CardContent className="p-6">
                    <div className="flex justify-between items-start mb-3">
                      <h3 className="font-semibold text-primary-800">{site.name}</h3>
                      <div className="flex gap-1">
                        <button
                          onClick={() => { setEditingSite(site); setShowSiteForm(true); }}
                          className="p-1 text-primary-500 hover:text-primary-700"
                        >
                          <Pencil className="h-4 w-4" />
                        </button>
                      </div>
                    </div>
                    <p className="text-sm text-primary-600 mb-2">{site.address}</p>
                    <p className="text-sm text-primary-500">
                      {site.openTime} - {site.closeTime}
                    </p>
                    {site.phone && (
                      <p className="text-sm text-primary-500 mt-1">{site.phone}</p>
                    )}
                    <div className="mt-3">
                      <span
                        className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                          site.isActive
                            ? "bg-accent/10 text-accent-700"
                            : "bg-gray-100 text-gray-600"
                        }`}
                      >
                        {site.isActive ? "Activa" : "Inactiva"}
                      </span>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          {/* Site Form Modal */}
          {showSiteForm && (
            <SiteFormModal
              site={editingSite}
              onSave={handleSaveSite}
              onClose={() => { setShowSiteForm(false); setEditingSite(null); }}
              loading={loading}
            />
          )}
        </TabsContent>

        {/* Courts Tab */}
        <TabsContent value="courts" className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-lg font-semibold text-primary-800">Canchas</h2>
            <Button onClick={() => { setEditingCourt(null); setShowCourtForm(true); }}>
              <Plus className="h-4 w-4 mr-2" />
              Nueva Cancha
            </Button>
          </div>

          {loadingCourts ? (
            <div className="space-y-2">
              {[1, 2, 3].map((i) => (
                <div key={i} className="animate-pulse bg-white p-4 rounded-lg border">
                  <div className="h-5 bg-primary-100 rounded w-1/4 mb-2" />
                  <div className="h-4 bg-primary-100 rounded w-1/2" />
                </div>
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="p-0">
                <table className="w-full">
                  <thead className="bg-primary-50 border-b border-primary-100">
                    <tr>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Cancha</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Sede</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Tipo</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Precio/hora</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Estado</th>
                      <th className="text-right px-4 py-3 text-sm font-medium text-primary-700">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {courts.map((court) => (
                      <tr key={court.id} className="border-b border-primary-50 hover:bg-primary-50/50">
                        <td className="px-4 py-3 font-medium text-primary-800">{court.name}</td>
                        <td className="px-4 py-3 text-primary-600">{court.site?.name || "-"}</td>
                        <td className="px-4 py-3 text-primary-600 capitalize">{court.type}</td>
                        <td className="px-4 py-3 text-primary-600">${court.hourlyRate}</td>
                        <td className="px-4 py-3">
                          <span
                            className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                              court.status === "active"
                                ? "bg-accent/10 text-accent-700"
                                : court.status === "maintenance"
                                ? "bg-amber-100 text-amber-700"
                                : "bg-gray-100 text-gray-600"
                            }`}
                          >
                            {court.status === "active" ? "Activa" : court.status === "maintenance" ? "Mantenimiento" : "Inactiva"}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <button
                            onClick={() => { setEditingCourt(court); setShowCourtForm(true); }}
                            className="p-1 text-primary-500 hover:text-primary-700 mr-1"
                          >
                            <Pencil className="h-4 w-4" />
                          </button>
                          <button
                            onClick={() => handleDeleteCourt(court.id)}
                            className="p-1 text-red-500 hover:text-red-700"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </CardContent>
            </Card>
          )}

          {/* Court Form Modal */}
          {showCourtForm && (
            <CourtFormModal
              court={editingCourt}
              sites={sites}
              onSave={handleSaveCourt}
              onClose={() => { setShowCourtForm(false); setEditingCourt(null); }}
              loading={loading}
            />
          )}
        </TabsContent>

        {/* Users Tab */}
        <TabsContent value="users" className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-lg font-semibold text-primary-800">Usuarios</h2>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Nuevo Usuario
            </Button>
          </div>

          {loadingUsers ? (
            <div className="space-y-2">
              {[1, 2, 3].map((i) => (
                <div key={i} className="animate-pulse bg-white p-4 rounded-lg border">
                  <div className="h-5 bg-primary-100 rounded w-1/4 mb-2" />
                  <div className="h-4 bg-primary-100 rounded w-1/2" />
                </div>
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="p-0">
                <table className="w-full">
                  <thead className="bg-primary-50 border-b border-primary-100">
                    <tr>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Usuario</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Email</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Rol</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Sede</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Estado</th>
                      <th className="text-right px-4 py-3 text-sm font-medium text-primary-700">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.map((user) => (
                      <tr key={user.id} className="border-b border-primary-50 hover:bg-primary-50/50">
                        <td className="px-4 py-3 font-medium text-primary-800">
                          {user.firstName} {user.lastName}
                        </td>
                        <td className="px-4 py-3 text-primary-600">{user.email}</td>
                        <td className="px-4 py-3">
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-primary-100 text-primary-700">
                            {user.role === "super_admin" ? "Super Admin" :
                             user.role === "site_admin" ? "Admin Sede" :
                             user.role === "staff" ? "Staff" : user.role}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-primary-600">{user.site?.name || "Todas"}</td>
                        <td className="px-4 py-3">
                          <span
                            className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                              user.isActive
                                ? "bg-accent/10 text-accent-700"
                                : "bg-gray-100 text-gray-600"
                            }`}
                          >
                            {user.isActive ? "Activo" : "Inactivo"}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <button className="p-1 text-primary-500 hover:text-primary-700">
                            <Pencil className="h-4 w-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}

// Site Form Modal Component
function SiteFormModal({
  site,
  onSave,
  onClose,
  loading,
}: {
  site: Site | null;
  onSave: (site: Partial<Site>) => void;
  onClose: () => void;
  loading: boolean;
}) {
  const [name, setName] = useState(site?.name || "");
  const [address, setAddress] = useState(site?.address || "");
  const [phone, setPhone] = useState(site?.phone || "");
  const [openTime, setOpenTime] = useState(site?.openTime || "08:00");
  const [closeTime, setCloseTime] = useState(site?.closeTime || "22:00");
  const [isActive, setIsActive] = useState(site?.isActive ?? true);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({ name, address, phone, openTime, closeTime, isActive });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-md mx-4">
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="text-lg font-semibold text-primary-800">
            {site ? "Editar Sede" : "Nueva Sede"}
          </h3>
          <button onClick={onClose} className="text-primary-500 hover:text-primary-700">
            <X className="h-5 w-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Nombre</label>
            <Input value={name} onChange={(e) => setName(e.target.value)} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Dirección</label>
            <Input value={address} onChange={(e) => setAddress(e.target.value)} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Teléfono</label>
            <Input value={phone} onChange={(e) => setPhone(e.target.value)} />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">Hora apertura</label>
              <Input type="time" value={openTime} onChange={(e) => setOpenTime(e.target.value)} />
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">Hora cierre</label>
              <Input type="time" value={closeTime} onChange={(e) => setCloseTime(e.target.value)} />
            </div>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="isActive"
              checked={isActive}
              onChange={(e) => setIsActive(e.target.checked)}
              className="rounded border-primary-300"
            />
            <label htmlFor="isActive" className="text-sm text-primary-700">Sede activa</label>
          </div>
          <div className="flex gap-3 pt-4">
            <Button type="button" variant="outline" onClick={onClose} className="flex-1">
              Cancelar
            </Button>
            <Button type="submit" disabled={loading} className="flex-1">
              {loading ? "Guardando..." : "Guardar"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}

// Court Form Modal Component
function CourtFormModal({
  court,
  sites,
  onSave,
  onClose,
  loading,
}: {
  court: Court | null;
  sites: Site[];
  onSave: (court: Partial<Court>) => void;
  onClose: () => void;
  loading: boolean;
}) {
  const [name, setName] = useState(court?.name || "");
  const [siteId, setSiteId] = useState(court?.siteId || sites[0]?.id || "");
  const [type, setType] = useState(court?.type || "indoor");
  const [hourlyRate, setHourlyRate] = useState(court?.hourlyRate?.toString() || "300");
  const [peakHourlyRate, setPeakHourlyRate] = useState(court?.peakHourlyRate?.toString() || "");
  const [status, setStatus] = useState(court?.status || "active");

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      name,
      siteId,
      type,
      hourlyRate: parseFloat(hourlyRate),
      peakHourlyRate: peakHourlyRate ? parseFloat(peakHourlyRate) : null,
      status,
    });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-md mx-4">
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="text-lg font-semibold text-primary-800">
            {court ? "Editar Cancha" : "Nueva Cancha"}
          </h3>
          <button onClick={onClose} className="text-primary-500 hover:text-primary-700">
            <X className="h-5 w-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Nombre</label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Cancha 1" required />
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Sede</label>
            <select
              value={siteId}
              onChange={(e) => setSiteId(e.target.value)}
              className="w-full rounded-lg border border-primary-200 bg-white px-3 py-2 text-sm"
              required
            >
              {sites.map((site) => (
                <option key={site.id} value={site.id}>{site.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Tipo</label>
            <select
              value={type}
              onChange={(e) => setType(e.target.value)}
              className="w-full rounded-lg border border-primary-200 bg-white px-3 py-2 text-sm"
            >
              <option value="indoor">Indoor</option>
              <option value="outdoor">Outdoor</option>
              <option value="covered">Techada</option>
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">Precio/hora</label>
              <Input
                type="number"
                value={hourlyRate}
                onChange={(e) => setHourlyRate(e.target.value)}
                min="0"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">Precio hora pico</label>
              <Input
                type="number"
                value={peakHourlyRate}
                onChange={(e) => setPeakHourlyRate(e.target.value)}
                min="0"
                placeholder="Opcional"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Estado</label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="w-full rounded-lg border border-primary-200 bg-white px-3 py-2 text-sm"
            >
              <option value="active">Activa</option>
              <option value="maintenance">Mantenimiento</option>
              <option value="inactive">Inactiva</option>
            </select>
          </div>
          <div className="flex gap-3 pt-4">
            <Button type="button" variant="outline" onClick={onClose} className="flex-1">
              Cancelar
            </Button>
            <Button type="submit" disabled={loading} className="flex-1">
              {loading ? "Guardando..." : "Guardar"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
