"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 };
  isOpenPlay?: boolean;
}

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();
        // Courts API returns array directly, map pricePerHour to hourlyRate for frontend
        const courtsArray = Array.isArray(data) ? data : data.data || [];
        setCourts(courtsArray.map((c: Record<string, unknown>) => ({
          ...c,
          hourlyRate: c.pricePerHour ?? c.hourlyRate,
        })));
      }
    } 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: "Settings saved successfully" });
    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 ? "Site updated" : "Site created" });
        fetchSites();
        setShowSiteForm(false);
        setEditingSite(null);
      } else {
        setMessage({ type: "error", text: "Error saving site" });
      }
    } catch (error) {
      setMessage({ type: "error", text: "Connection error" });
    } 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 ? "Court updated" : "Court created" });
        fetchCourts();
        setShowCourtForm(false);
        setEditingCourt(null);
      } else {
        setMessage({ type: "error", text: "Error saving court" });
      }
    } catch (error) {
      setMessage({ type: "error", text: "Connection error" });
    } finally {
      setLoading(false);
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleDeleteCourt = async (courtId: string) => {
    if (!confirm("Are you sure you want to delete this court?")) return;

    try {
      const res = await fetch(`/api/courts/${courtId}`, { method: "DELETE" });
      if (res.ok) {
        setMessage({ type: "success", text: "Court deleted" });
        fetchCourts();
      } else {
        setMessage({ type: "error", text: "Error deleting court" });
      }
    } catch (error) {
      setMessage({ type: "error", text: "Connection error" });
    }
    setTimeout(() => setMessage(null), 3000);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-primary-800">Settings</h1>
        <p className="text-primary-600">Manage system settings</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">Organization</span>
          </TabsTrigger>
          <TabsTrigger value="sites" className="gap-2">
            <MapPin className="h-4 w-4" />
            <span className="hidden sm:inline">Sites</span>
          </TabsTrigger>
          <TabsTrigger value="courts" className="gap-2">
            <Clock className="h-4 w-4" />
            <span className="hidden sm:inline">Courts</span>
          </TabsTrigger>
          <TabsTrigger value="users" className="gap-2">
            <Users className="h-4 w-4" />
            <span className="hidden sm:inline">Users</span>
          </TabsTrigger>
        </TabsList>

        {/* Organization Tab */}
        <TabsContent value="organization" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Organization Information</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">
                    Organization name
                  </label>
                  <Input
                    value={orgName}
                    onChange={(e) => setOrgName(e.target.value)}
                    placeholder="Name"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Contact email
                  </label>
                  <Input
                    type="email"
                    value={orgEmail}
                    onChange={(e) => setOrgEmail(e.target.value)}
                    placeholder="email@example.com"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Phone
                  </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">
                    Currency
                  </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 - Mexican Peso</option>
                    <option value="USD">USD - US Dollar</option>
                    <option value="EUR">EUR - Euro</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Timezone
                  </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">Mexico City</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 ? "Saving..." : "Save changes"}
                </Button>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Booking Settings</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">
                    Default duration (minutes)
                  </label>
                  <Input type="number" defaultValue={60} min={30} step={30} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Minimum notice (hours)
                  </label>
                  <Input type="number" defaultValue={2} min={0} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Maximum advance (days)
                  </label>
                  <Input type="number" defaultValue={14} min={1} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-primary-700 mb-1">
                    Cancellation window (hours)
                  </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 ? "Saving..." : "Save changes"}
                </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">Sites</h2>
            <Button onClick={() => { setEditingSite(null); setShowSiteForm(true); }}>
              <Plus className="h-4 w-4 mr-2" />
              New Site
            </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 ? "Active" : "Inactive"}
                      </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">Courts</h2>
            <Button onClick={() => { setEditingCourt(null); setShowCourtForm(true); }}>
              <Plus className="h-4 w-4 mr-2" />
              New Court
            </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">Court</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Site</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Type</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Price/hour</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Status</th>
                      <th className="text-right px-4 py-3 text-sm font-medium text-primary-700">Actions</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}
                          {court.isOpenPlay && (
                            <span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">
                              Open Play
                            </span>
                          )}
                        </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 ${
                              ["active", "AVAILABLE"].includes(court.status)
                                ? "bg-accent/10 text-accent-700"
                                : ["maintenance", "MAINTENANCE"].includes(court.status)
                                ? "bg-amber-100 text-amber-700"
                                : "bg-gray-100 text-gray-600"
                            }`}
                          >
                            {["active", "AVAILABLE"].includes(court.status) ? "Active" : ["maintenance", "MAINTENANCE"].includes(court.status) ? "Maintenance" : "Inactive"}
                          </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">Users</h2>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              New User
            </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">User</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">Role</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Site</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-primary-700">Status</th>
                      <th className="text-right px-4 py-3 text-sm font-medium text-primary-700">Actions</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" ? "Site Admin" :
                             user.role === "staff" ? "Staff" : user.role}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-primary-600">{user.site?.name || "All"}</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 ? "Active" : "Inactive"}
                          </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 ? "Edit Site" : "New Site"}
          </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">Name</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">Address</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">Phone</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">Opening time</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">Closing time</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">Site active</label>
          </div>
          <div className="flex gap-3 pt-4">
            <Button type="button" variant="outline" onClick={onClose} className="flex-1">
              Cancel
            </Button>
            <Button type="submit" disabled={loading} className="flex-1">
              {loading ? "Saving..." : "Save"}
            </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 [isOpenPlay, setIsOpenPlay] = useState(court?.isOpenPlay ?? false);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      name,
      siteId,
      type,
      hourlyRate: parseFloat(hourlyRate),
      pricePerHour: parseFloat(hourlyRate),
      peakHourlyRate: peakHourlyRate ? parseFloat(peakHourlyRate) : null,
      status,
      isOpenPlay,
    } as Partial<Court> & { pricePerHour?: number });
  };

  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 ? "Edit Court" : "New Court"}
          </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">Name</label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Court 1" required />
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Site</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">Type</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">Covered</option>
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">Price/hour</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">Peak hour price</label>
              <Input
                type="number"
                value={peakHourlyRate}
                onChange={(e) => setPeakHourlyRate(e.target.value)}
                min="0"
                placeholder="Optional"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">Status</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">Active</option>
              <option value="maintenance">Maintenance</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="isOpenPlay"
              checked={isOpenPlay}
              onChange={(e) => setIsOpenPlay(e.target.checked)}
              className="rounded border-primary-300"
            />
            <label htmlFor="isOpenPlay" className="text-sm text-primary-700">
              Open Play Court (free, for group scheduling)
            </label>
          </div>
          <div className="flex gap-3 pt-4">
            <Button type="button" variant="outline" onClick={onClose} className="flex-1">
              Cancel
            </Button>
            <Button type="submit" disabled={loading} className="flex-1">
              {loading ? "Saving..." : "Save"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
