import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Trash2, Pencil, MapPin, CalendarDays, FileText, GripVertical, Eye, Loader2, X, DollarSign, ClipboardList } from "lucide-react";
import GoogleMapPicker, { type MapPinData } from "./GoogleMapPicker";
import ManageAmenityBookingsDialog from "./ManageAmenityBookingsDialog";

interface Props {
  associationId: string;
}

interface FormField {
  id: string;
  label: string;
  type: "text" | "email" | "phone" | "textarea" | "select" | "signature" | "date" | "checkbox" | "paragraph";
  required: boolean;
  options?: string[];
  content?: string;
}

interface Amenity {
  id: string;
  name: string;
  description: string | null;
  amenity_type: string;
  cover_image_url: string | null;
  map_config: any;
  booking_config: any;
  form_fields: FormField[];
  is_active: boolean;
  show_on_public_page?: boolean;
  show_on_homeowner_portal?: boolean;
  visible_to_roles?: string[];
  sort_order: number;
}

const ROLE_VISIBILITY_OPTIONS: { value: string; label: string }[] = [
  { value: "homeowner", label: "Homeowner" },
  { value: "board_member", label: "Board Member" },
  { value: "master_board_member", label: "Master Board Member" },
  { value: "arc_member", label: "ARC Member" },
  { value: "fining_member", label: "Fining Member" },
  { value: "rv_boat_lot", label: "RV/Boat Lot" },
  { value: "management", label: "Management" },
  { value: "association_management", label: "Association Management" },
  { value: "legal", label: "Legal" },
];

interface RentalFeeOption {
  id: string;
  label: string;
  amount: number;
}

const amenityTypes = [
  { value: "map", label: "Map Location", icon: MapPin, desc: "Pin on Google Maps with name & description" },
  { value: "booking", label: "Calendar Booking", icon: CalendarDays, desc: "Visitors can request time slot bookings" },
  { value: "rental_calendar", label: "Rental Calendar", icon: CalendarDays, desc: "Rental booking calendar with public blocked availability" },
  { value: "meeting_calendar", label: "Meeting Calendar", icon: ClipboardList, desc: "Meeting booking calendar with private blocked availability" },
  { value: "form", label: "Form", icon: FileText, desc: "Custom form with signature support" },
];

const fieldTypes = [
  { value: "text", label: "Text" },
  { value: "email", label: "Email" },
  { value: "phone", label: "Phone" },
  { value: "textarea", label: "Long Text" },
  { value: "date", label: "Date" },
  { value: "select", label: "Dropdown" },
  { value: "checkbox", label: "Checkbox / Agreement" },
  { value: "signature", label: "Signature" },
  { value: "paragraph", label: "Text Paragraph (display only)" },
];

function FormFieldBuilder({ fields, onChange }: { fields: FormField[]; onChange: (f: FormField[]) => void }) {
  const addField = () => {
    onChange([...fields, {
      id: Math.random().toString(36).substr(2, 9),
      label: "",
      type: "text",
      required: false,
    }]);
  };

  const updateField = (id: string, updates: Partial<FormField>) => {
    onChange(fields.map(f => f.id === id ? { ...f, ...updates } : f));
  };

  const removeField = (id: string) => {
    onChange(fields.filter(f => f.id !== id));
  };

  return (
    <div className="space-y-3">
      {fields.map((field, idx) => (
        <div key={field.id} className="flex items-start gap-2 p-3 rounded-lg border bg-background">
          <span className="text-xs text-muted-foreground mt-2 w-5 shrink-0">{idx + 1}</span>
          <div className="flex-1 grid grid-cols-2 gap-2">
            <Input
              placeholder={field.type === "paragraph" ? "Heading (optional)" : "Field label"}
              value={field.label}
              onChange={e => updateField(field.id, { label: e.target.value })}
              className="text-sm"
            />
            <Select value={field.type} onValueChange={v => updateField(field.id, { type: v as any })}>
              <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
              <SelectContent>
                {fieldTypes.map(ft => <SelectItem key={ft.value} value={ft.value}>{ft.label}</SelectItem>)}
              </SelectContent>
            </Select>
            {field.type === "paragraph" && (
              <div className="col-span-2">
                <Textarea
                  placeholder="Paragraph text shown to the user (instructions, disclaimers, etc.)"
                  value={field.content || ""}
                  onChange={e => updateField(field.id, { content: e.target.value })}
                  rows={4}
                  className="text-sm"
                />
              </div>
            )}
            {field.type === "select" && (
              <div className="col-span-2">
                <Input
                  placeholder="Options (comma-separated)"
                  value={(field.options || []).join(", ")}
                  onChange={e => updateField(field.id, { options: e.target.value.split(",").map(s => s.trim()).filter(Boolean) })}
                  className="text-sm"
                />
              </div>
            )}
            {field.type === "checkbox" && (
              <div className="col-span-2">
                <Input
                  placeholder="Agreement text shown next to checkbox"
                  value={field.label}
                  onChange={e => updateField(field.id, { label: e.target.value })}
                  className="text-sm"
                />
              </div>
            )}
            {field.type !== "paragraph" && (
              <div className="col-span-2 flex items-center gap-2">
                <Switch checked={field.required} onCheckedChange={v => updateField(field.id, { required: v })} />
                <Label className="text-xs">Required</Label>
              </div>
            )}
          </div>
          <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive" onClick={() => removeField(field.id)}>
            <X className="h-3.5 w-3.5" />
          </Button>
        </div>
      ))}
      <Button variant="outline" size="sm" className="gap-1.5" onClick={addField}>
        <Plus className="h-3.5 w-3.5" /> Add Field
      </Button>
    </div>
  );
}

function RentalFeeOptionsBuilder({ options, onChange }: { options: RentalFeeOption[]; onChange: (options: RentalFeeOption[]) => void }) {
  const addOption = () => onChange([...options, { id: Math.random().toString(36).slice(2, 9), label: "", amount: 0 }]);
  const updateOption = (id: string, updates: Partial<RentalFeeOption>) => onChange(options.map(option => option.id === id ? { ...option, ...updates } : option));
  const removeOption = (id: string) => onChange(options.filter(option => option.id !== id));

  return (
    <div className="space-y-3">
      {options.map(option => (
        <div key={option.id} className="grid grid-cols-[1fr_140px_32px] gap-2 items-center">
          <Input value={option.label} onChange={e => updateOption(option.id, { label: e.target.value })} placeholder="Fee name" className="text-sm" />
          <Input value={option.amount || ""} onChange={e => updateOption(option.id, { amount: Number(e.target.value) || 0 })} type="number" min="0" step="0.01" placeholder="0.00" className="text-sm" />
          <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive" onClick={() => removeOption(option.id)}>
            <X className="h-3.5 w-3.5" />
          </Button>
        </div>
      ))}
      <Button variant="outline" size="sm" className="gap-1.5" onClick={addOption}>
        <Plus className="h-3.5 w-3.5" /> Add Fee Option
      </Button>
    </div>
  );
}

export default function AmenitiesManager({ associationId }: Props) {
  const { toast } = useToast();
  const db = supabase as any;

  const [amenities, setAmenities] = useState<Amenity[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [bookingsDialogAmenity, setBookingsDialogAmenity] = useState<any>(null);

  // Form state
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [amenityType, setAmenityType] = useState("map");
  const [coverImageUrl, setCoverImageUrl] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [showOnPublicPage, setShowOnPublicPage] = useState(true);
  const [showOnHomeownerPortal, setShowOnHomeownerPortal] = useState(true);
  const [visibleToRoles, setVisibleToRoles] = useState<string[]>([]);

  // Map config - multiple pins
  const [mapPins, setMapPins] = useState<MapPinData[]>([]);
  const [mapZoom, setMapZoom] = useState<number>(16);
  const [mapLockedView, setMapLockedView] = useState<{ lat: number; lng: number; zoom: number } | null>(null);
  const [reservationFee, setReservationFee] = useState("");
  const [reservationFormFields, setReservationFormFields] = useState<FormField[]>([]);

  // Booking config
  const [bookingSlotDuration, setBookingSlotDuration] = useState("60");
  const [bookingStartTime, setBookingStartTime] = useState("09:00");
  const [bookingEndTime, setBookingEndTime] = useState("17:00");
  const [securityDeposit, setSecurityDeposit] = useState("");
  const [rentalFeeOptions, setRentalFeeOptions] = useState<RentalFeeOption[]>([]);

  // Form fields
  const [formFields, setFormFields] = useState<FormField[]>([]);

  // Signable PDF documents (templates attached to amenity)
  const [signableDocuments, setSignableDocuments] = useState<{ id: string; name: string; url: string; required: boolean }[]>([]);
  const [uploadingDoc, setUploadingDoc] = useState(false);

  const handleSignableDocUpload = async (file: File) => {
    if (file.type !== "application/pdf") {
      toast({ title: "PDF only", description: "Please upload a PDF file.", variant: "destructive" });
      return;
    }
    setUploadingDoc(true);
    const path = `templates/${associationId}/${Date.now()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, "_")}`;
    const { error: upErr } = await supabase.storage.from("amenity-documents").upload(path, file, { upsert: false, contentType: "application/pdf" });
    if (upErr) {
      setUploadingDoc(false);
      toast({ title: "Upload failed", description: upErr.message, variant: "destructive" });
      return;
    }
    const { data: pub } = supabase.storage.from("amenity-documents").getPublicUrl(path);
    setSignableDocuments(prev => [...prev, { id: Math.random().toString(36).slice(2, 10), name: file.name, url: pub.publicUrl, required: true }]);
    setUploadingDoc(false);
  };

  useEffect(() => { loadAmenities(); }, [associationId]);

  const loadAmenities = async () => {
    setLoading(true);
    const { data, error } = await db
      .from("amenities")
      .select("*")
      .eq("association_id", associationId)
      .order("sort_order");
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else setAmenities(data || []);
    setLoading(false);
  };

  const resetForm = () => {
    setEditingId(null);
    setName("");
    setDescription("");
    setAmenityType("map");
    setCoverImageUrl("");
    setIsActive(true);
    setShowOnPublicPage(true);
    setShowOnHomeownerPortal(true);
    setVisibleToRoles([]);
    setMapPins([]);
    setMapZoom(16);
    setMapLockedView(null);
    setReservationFee("");
    setReservationFormFields([]);
    setBookingSlotDuration("60");
    setBookingStartTime("09:00");
    setBookingEndTime("17:00");
    setSecurityDeposit("");
    setRentalFeeOptions([]);
    setFormFields([]);
    setSignableDocuments([]);
  };

  const openCreate = () => { resetForm(); setDialogOpen(true); };

  const openEdit = (a: Amenity) => {
    setEditingId(a.id);
    setName(a.name);
    setDescription(a.description || "");
    setAmenityType(a.amenity_type);
    setCoverImageUrl(a.cover_image_url || "");
    setIsActive(a.is_active);
    setShowOnPublicPage(a.show_on_public_page ?? true);
    setShowOnHomeownerPortal(a.show_on_homeowner_portal ?? true);
    setVisibleToRoles(Array.isArray((a as any).visible_to_roles) ? (a as any).visible_to_roles : []);
    const mc = a.map_config || {};
    if (Array.isArray(mc.pins)) {
      setMapPins(mc.pins);
    } else if (mc.lat && mc.lng) {
      setMapPins([{ id: "legacy", label: mc.label || a.name, lat: mc.lat.toString(), lng: mc.lng.toString(), status: "available" }]);
    } else {
      setMapPins([]);
    }
    setMapZoom(mc.zoom ?? 16);
    setMapLockedView(mc.locked_view && typeof mc.locked_view.lat === "number" && typeof mc.locked_view.lng === "number" ? mc.locked_view : null);
    setReservationFormFields(Array.isArray(mc.reservation_form_fields) ? mc.reservation_form_fields : []);
    const bc = a.booking_config || {};
    setBookingSlotDuration(bc.slot_duration?.toString() || "60");
    setBookingStartTime(bc.start_time || "09:00");
    setBookingEndTime(bc.end_time || "17:00");
    setReservationFee((a.amenity_type === "rental_calendar" ? bc.rental_fee : mc.reservation_fee)?.toString() || "");
    setSecurityDeposit(bc.security_deposit?.toString() || "");
    setRentalFeeOptions(Array.isArray(bc.fee_options) ? bc.fee_options : []);
    setFormFields(Array.isArray(a.form_fields) ? a.form_fields : []);
    setSignableDocuments(Array.isArray((a as any).signable_documents) ? (a as any).signable_documents : []);
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (!name.trim()) {
      toast({ title: "Name required", variant: "destructive" });
      return;
    }
    setSaving(true);

    const payload: any = {
      association_id: associationId,
      name: name.trim(),
      description: description || null,
      amenity_type: amenityType,
      cover_image_url: coverImageUrl || null,
      is_active: isActive,
      show_on_public_page: showOnPublicPage,
      show_on_homeowner_portal: showOnHomeownerPortal,
      visible_to_roles: visibleToRoles,
      map_config: amenityType === "map" ? {
        pins: mapPins,
        zoom: mapZoom,
        locked_view: mapLockedView,
        reservation_fee: reservationFee ? parseFloat(reservationFee) : null,
        reservation_form_fields: reservationFormFields,
      } : {},
      booking_config: ["booking", "rental_calendar", "meeting_calendar"].includes(amenityType) ? {
        slot_duration: parseInt(bookingSlotDuration) || 60,
        start_time: bookingStartTime,
        end_time: bookingEndTime,
        rental_fee: amenityType === "rental_calendar" && reservationFee ? parseFloat(reservationFee) : null,
        security_deposit: amenityType === "rental_calendar" && securityDeposit ? parseFloat(securityDeposit) : null,
        fee_options: amenityType === "rental_calendar" ? rentalFeeOptions.filter(option => option.label.trim() && option.amount > 0) : undefined,
        pass_processing_fees: amenityType === "rental_calendar" ? true : undefined,
      } : {},
      form_fields: ["form", "rental_calendar", "meeting_calendar"].includes(amenityType) ? formFields : [],
      signable_documents: ["booking", "rental_calendar", "meeting_calendar"].includes(amenityType) ? signableDocuments : [],
      updated_at: new Date().toISOString(),
    };

    let error;
    if (editingId) {
      ({ error } = await db.from("amenities").update(payload).eq("id", editingId));
    } else {
      payload.sort_order = amenities.length;
      ({ error } = await db.from("amenities").insert(payload));
    }

    setSaving(false);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: editingId ? "Amenity updated" : "Amenity created" });
      setDialogOpen(false);
      loadAmenities();
    }
  };

  const handleDelete = async (id: string) => {
    const { error } = await db.from("amenities").delete().eq("id", id);
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else { toast({ title: "Amenity deleted" }); loadAmenities(); }
  };

  const togglePublicDisplay = async (amenity: Amenity, checked: boolean) => {
    setAmenities(prev => prev.map(a => a.id === amenity.id ? { ...a, show_on_public_page: checked } : a));
    const { error } = await db.from("amenities").update({ show_on_public_page: checked, updated_at: new Date().toISOString() }).eq("id", amenity.id);
    if (error) {
      setAmenities(prev => prev.map(a => a.id === amenity.id ? { ...a, show_on_public_page: amenity.show_on_public_page } : a));
      toast({ title: "Error", description: error.message, variant: "destructive" });
    }
  };

  const toggleHomeownerDisplay = async (amenity: Amenity, checked: boolean) => {
    setAmenities(prev => prev.map(a => a.id === amenity.id ? { ...a, show_on_homeowner_portal: checked } : a));
    const { error } = await db.from("amenities").update({ show_on_homeowner_portal: checked, updated_at: new Date().toISOString() }).eq("id", amenity.id);
    if (error) {
      setAmenities(prev => prev.map(a => a.id === amenity.id ? { ...a, show_on_homeowner_portal: amenity.show_on_homeowner_portal } : a));
      toast({ title: "Error", description: error.message, variant: "destructive" });
    }
  };

  const typeInfo = amenityTypes.find(t => t.value === amenityType);

  if (loading) {
    return <div className="flex items-center gap-2 text-muted-foreground text-sm py-6"><Loader2 className="h-4 w-4 animate-spin" /> Loading amenities...</div>;
  }

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-base font-semibold">Amenities</h3>
          <p className="text-sm text-muted-foreground mt-0.5">
            Manage amenities and choose which ones display on the public page and homeowner portal.
          </p>
        </div>
        <Button onClick={openCreate} size="sm" className="gap-1.5">
          <Plus className="h-4 w-4" /> Add Amenity
        </Button>
      </div>

      {amenities.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            <MapPin className="h-8 w-8 mx-auto mb-2 opacity-40" />
            <p>No amenities yet. Add map locations, booking calendars, or forms.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="rounded-lg border bg-card overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-xs font-bold uppercase">Name</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[120px]">Type</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[80px]">Status</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[120px]">Public Page</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[140px]">Homeowner View</TableHead>
                <TableHead className="text-xs font-bold uppercase w-[100px] text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {amenities.map(a => {
                const ti = amenityTypes.find(t => t.value === a.amenity_type);
                const Icon = ti?.icon || MapPin;
                return (
                  <TableRow key={a.id}>
                    <TableCell>
                      <div className="flex items-center gap-3">
                        <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
                        <div>
                          <p className="font-medium text-sm">{a.name}</p>
                          {a.description && <p className="text-xs text-muted-foreground line-clamp-1">{a.description}</p>}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-xs capitalize">{ti?.label || a.amenity_type}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={a.is_active ? "default" : "secondary"} className="text-xs">
                        {a.is_active ? "Active" : "Inactive"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Switch checked={a.show_on_public_page ?? true} onCheckedChange={checked => togglePublicDisplay(a, checked)} disabled={a.amenity_type === "meeting_calendar"} />
                    </TableCell>
                    <TableCell>
                      <Switch checked={a.show_on_homeowner_portal ?? true} onCheckedChange={checked => toggleHomeownerDisplay(a, checked)} />
                    </TableCell>
                    <TableCell>
                      <div className="flex justify-end gap-1">
                        {["booking", "rental_calendar", "meeting_calendar"].includes(a.amenity_type) && (
                          <Button variant="ghost" size="icon" className="h-8 w-8" title="Manage bookings" onClick={() => setBookingsDialogAmenity(a)}>
                            <CalendarDays className="h-4 w-4" />
                          </Button>
                        )}
                        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(a)}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDelete(a.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[650px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingId ? "Edit Amenity" : "Add Amenity"}</DialogTitle>
          </DialogHeader>

          <div className="space-y-5">
            {/* Basic Info */}
            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2 space-y-1.5">
                <Label>Name *</Label>
                <Input value={name} onChange={e => setName(e.target.value)} placeholder="Pool, Clubhouse, Tennis Court..." />
              </div>
              <div className="col-span-2 space-y-1.5">
                <Label>Description</Label>
                <Textarea value={description} onChange={e => setDescription(e.target.value)} rows={2} placeholder="Brief description shown to visitors" />
              </div>
              <div className="space-y-1.5">
                <Label>Type</Label>
                <Select value={amenityType} onValueChange={setAmenityType}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {amenityTypes.map(t => (
                      <SelectItem key={t.value} value={t.value}>
                        <span className="flex items-center gap-2">
                          <t.icon className="h-4 w-4" /> {t.label}
                        </span>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground">{typeInfo?.desc}</p>
              </div>
              <div className="space-y-1.5">
                <Label>Cover Image URL</Label>
                <Input value={coverImageUrl} onChange={e => setCoverImageUrl(e.target.value)} placeholder="https://..." />
              </div>
            </div>

            <div className="flex items-center justify-between">
              <Label>Active</Label>
              <Switch checked={isActive} onCheckedChange={setIsActive} />
            </div>

            {amenityType !== "meeting_calendar" && (
              <div className="flex items-center justify-between rounded-lg border bg-background p-3">
                <div>
                  <Label>Show on Public Page</Label>
                  <p className="text-xs text-muted-foreground mt-0.5">Turn this off to hide the amenity from this association’s public page.</p>
                </div>
                <Switch checked={showOnPublicPage} onCheckedChange={setShowOnPublicPage} />
              </div>
            )}

            <div className="flex items-center justify-between rounded-lg border bg-background p-3">
              <div>
                <Label>Show on Homeowner View</Label>
                <p className="text-xs text-muted-foreground mt-0.5">Turn this off to hide the amenity from homeowners in this association.</p>
              </div>
              <Switch checked={showOnHomeownerPortal} onCheckedChange={setShowOnHomeownerPortal} />
            </div>

            <div className="rounded-lg border bg-background p-3 space-y-2">
              <div>
                <Label>Calendar Visible To Roles</Label>
                <p className="text-xs text-muted-foreground mt-0.5">Select which portal roles can view this amenity's calendar. Staff (admin/manager/employee) always see all amenities.</p>
              </div>
              <div className="flex flex-wrap gap-2 pt-1">
                {ROLE_VISIBILITY_OPTIONS.map(opt => {
                  const checked = visibleToRoles.includes(opt.value);
                  return (
                    <button
                      key={opt.value}
                      type="button"
                      onClick={() => setVisibleToRoles(prev => checked ? prev.filter(r => r !== opt.value) : [...prev, opt.value])}
                      className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${checked ? "bg-primary text-primary-foreground border-primary" : "bg-background text-muted-foreground border-border hover:bg-muted"}`}
                    >
                      {opt.label}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Map Config - Multiple Pins */}
            {amenityType === "map" && (
              <div className="space-y-4">
                <GoogleMapPicker
                  pins={mapPins}
                  onChange={setMapPins}
                  zoom={mapZoom}
                  onZoomChange={setMapZoom}
                  lockedView={mapLockedView}
                  onLockedViewChange={setMapLockedView}
                  formAmenities={amenities.filter(a => a.amenity_type === "form" && a.id !== editingId).map(a => ({ id: a.id, name: a.name }))}
                />
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm flex items-center gap-2">
                      <DollarSign className="h-4 w-4" /> Reservation Fee
                    </CardTitle>
                    <CardDescription className="text-xs">
                      Optional fee charged when reserving an available location. Leave blank for free reservations.
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-center gap-2 max-w-xs">
                      <span className="text-sm font-medium text-muted-foreground">$</span>
                      <Input
                        type="number"
                        step="0.01"
                        min="0"
                        value={reservationFee}
                        onChange={e => setReservationFee(e.target.value)}
                        placeholder="0.00"
                        className="text-sm"
                      />
                    </div>
                  </CardContent>
                </Card>

                {/* Reservation Form Builder */}
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm flex items-center gap-2">
                      <ClipboardList className="h-4 w-4" /> Reservation Form Fields
                    </CardTitle>
                    <CardDescription className="text-xs">
                      Customize the fields shown on the reservation form. Name, email, date, and signature are always included.
                      Add additional fields like address, phone, agreements, dropdowns, etc.
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <FormFieldBuilder fields={reservationFormFields} onChange={setReservationFormFields} />
                  </CardContent>
                </Card>
              </div>
            )}

            {/* Booking Config */}
            {["booking", "rental_calendar", "meeting_calendar"].includes(amenityType) && (
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm flex items-center gap-2"><CalendarDays className="h-4 w-4" /> Booking Configuration</CardTitle>
                </CardHeader>
                <CardContent className="grid grid-cols-3 gap-3">
                  <div className="space-y-1">
                    <Label className="text-xs">Slot Duration (min)</Label>
                    <Input value={bookingSlotDuration} onChange={e => setBookingSlotDuration(e.target.value)} type="number" />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">Available From</Label>
                    <Input value={bookingStartTime} onChange={e => setBookingStartTime(e.target.value)} type="time" />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">Available Until</Label>
                    <Input value={bookingEndTime} onChange={e => setBookingEndTime(e.target.value)} type="time" />
                  </div>
                  {amenityType === "rental_calendar" && (
                    <div className="col-span-3 space-y-4 rounded-lg border bg-background p-3">
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div className="space-y-1">
                          <Label className="text-xs">Base Rental Fee</Label>
                          <Input value={reservationFee} onChange={e => setReservationFee(e.target.value)} type="number" min="0" step="0.01" placeholder="0.00" />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Security Deposit</Label>
                          <Input value={securityDeposit} onChange={e => setSecurityDeposit(e.target.value)} type="number" min="0" step="0.01" placeholder="0.00" />
                        </div>
                      </div>
                      <div className="space-y-2">
                        <Label className="text-xs">Selectable Fee Dropdown</Label>
                        <RentalFeeOptionsBuilder options={rentalFeeOptions} onChange={setRentalFeeOptions} />
                      </div>
                      <p className="text-xs text-muted-foreground">Stripe checkout includes selected fees and passes processing fees to the renter.</p>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* Signable PDF documents */}
            {["booking", "rental_calendar", "meeting_calendar"].includes(amenityType) && (
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm flex items-center gap-2"><FileText className="h-4 w-4" /> Signable Documents</CardTitle>
                  <CardDescription className="text-xs">Upload PDFs (waivers, rental agreements). Bookers must sign each one before confirming.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-3">
                  {signableDocuments.length === 0 && (
                    <p className="text-xs text-muted-foreground">No documents attached yet.</p>
                  )}
                  {signableDocuments.map(doc => (
                    <div key={doc.id} className="flex items-center justify-between gap-2 border rounded-md p-2">
                      <div className="flex-1 min-w-0">
                        <a href={doc.url} target="_blank" rel="noopener noreferrer" className="text-sm font-medium truncate block hover:underline">{doc.name}</a>
                        <label className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
                          <input type="checkbox" checked={doc.required} onChange={(e) => setSignableDocuments(prev => prev.map(d => d.id === doc.id ? { ...d, required: e.target.checked } : d))} />
                          Required to sign
                        </label>
                      </div>
                      <Button type="button" variant="ghost" size="sm" onClick={() => setSignableDocuments(prev => prev.filter(d => d.id !== doc.id))}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  ))}
                  <div>
                    <Input type="file" accept="application/pdf" disabled={uploadingDoc} onChange={(e) => { const f = e.target.files?.[0]; if (f) { handleSignableDocUpload(f); e.target.value = ""; } }} />
                    {uploadingDoc && <p className="text-xs text-muted-foreground mt-1 flex items-center gap-1"><Loader2 className="h-3 w-3 animate-spin" /> Uploading...</p>}
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Form Builder */}
            {["form", "rental_calendar", "meeting_calendar"].includes(amenityType) && (
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm flex items-center gap-2"><FileText className="h-4 w-4" /> {amenityType === "rental_calendar" ? "Rental Intake Form" : amenityType === "meeting_calendar" ? "Meeting Request Form" : "Form Fields"}</CardTitle>
                  <CardDescription className="text-xs">Build the custom intake fields. Signature fields render a signature pad.</CardDescription>
                </CardHeader>
                <CardContent>
                  <FormFieldBuilder fields={formFields} onChange={setFormFields} />
                </CardContent>
              </Card>
            )}
          </div>

          <DialogFooter className="pt-4">
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving && <Loader2 className="h-4 w-4 animate-spin mr-1" />}
              {editingId ? "Update" : "Create"} Amenity
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <ManageAmenityBookingsDialog
        open={!!bookingsDialogAmenity}
        onOpenChange={(v) => { if (!v) setBookingsDialogAmenity(null); }}
        amenity={bookingsDialogAmenity}
      />
    </div>
  );
}
