"use client";

import { FormEvent, useCallback, useEffect, useState } from "react";
import { AlertTriangle, Edit3, Loader2, MapPin, Percent, Plus, Trash2, X } from "lucide-react";
import { Space_Grotesk } from "next/font/google";

import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import { adminRequest, type AdminLocation } from "@/lib/admin-api";

const spaceGrotesk = Space_Grotesk({
  subsets: ["latin"],
  weight: ["300", "400", "500", "600", "700"],
});

type LocationFormState = {
  id?: number;
  name: string;
  adjustmentType: "additional" | "discount";
  adjustmentValue: string;
  isActive: boolean;
};

const emptyForm: LocationFormState = {
  name: "",
  adjustmentType: "additional",
  adjustmentValue: "0",
  isActive: true,
};

function formatPercent(value: number) {
  return `${Number(value).toLocaleString("en-IN", {
    maximumFractionDigits: 2,
    minimumFractionDigits: value % 1 === 0 ? 0 : 2,
  })}%`;
}

function getAdjustmentLabel(location: AdminLocation) {
  if (location.discountPercentage > 0) {
    return `Discount ${formatPercent(location.discountPercentage)}`;
  }

  return `Additional cost +${formatPercent(location.additionalCostPercentage)}`;
}

export default function AdminLocationsPage() {
  const [locations, setLocations] = useState<AdminLocation[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeletingId, setIsDeletingId] = useState<number | null>(null);
  const [errorMessage, setErrorMessage] = useState("");
  const [form, setForm] = useState<LocationFormState | null>(null);
  const [pendingDeleteLocation, setPendingDeleteLocation] = useState<AdminLocation | null>(null);

  const loadLocations = useCallback(async () => {
    setIsLoading(true);
    setErrorMessage("");

    try {
      const data = await adminRequest<{ locations: AdminLocation[] }>("/api/admin/locations");

      setLocations(data.locations);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not load locations");
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadLocations();
  }, [loadLocations]);

  useEffect(() => {
    if (!form && !pendingDeleteLocation) {
      return;
    }

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [form, pendingDeleteLocation]);

  function openEditForm(location: AdminLocation) {
    const hasDiscount = location.discountPercentage > 0;

    setForm({
      id: location.id,
      name: location.name,
      adjustmentType: hasDiscount ? "discount" : "additional",
      adjustmentValue: String(
        hasDiscount ? location.discountPercentage : location.additionalCostPercentage,
      ),
      isActive: location.isActive,
    });
  }

  async function saveLocation(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (!form) {
      return;
    }

    setIsSaving(true);
    setErrorMessage("");

    try {
      const adjustmentValue = Number(form.adjustmentValue || 0);

      const payload = {
        name: form.name.trim(),
        additionalCostPercentage: form.adjustmentType === "additional" ? adjustmentValue : 0,
        discountPercentage: form.adjustmentType === "discount" ? adjustmentValue : 0,
        isActive: form.isActive,
      };

      if (form.id) {
        await adminRequest(`/api/admin/locations/${form.id}`, {
          method: "PUT",
          body: JSON.stringify(payload),
        });
      } else {
        await adminRequest("/api/admin/locations", {
          method: "POST",
          body: JSON.stringify(payload),
        });
      }

      setForm(null);

      await loadLocations();
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not save location");
    } finally {
      setIsSaving(false);
    }
  }

  async function deleteLocation(location: AdminLocation) {
    setIsDeletingId(location.id);
    setErrorMessage("");

    try {
      await adminRequest(`/api/admin/locations/${location.id}`, {
        method: "DELETE",
      });

      setPendingDeleteLocation(null);

      await loadLocations();
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not delete location");
    } finally {
      setIsDeletingId(null);
    }
  }

  return (
    <AdminGuard>
      <AdminShell
        title="Locations"
        lead="Manage city or area pricing adjustments for service bookings."
      >
        <section className="space-y-5">
          <div className="rounded-lg border border-border bg-white p-4 shadow-sm">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Pricing locations
                </p>

                <h2 className="mt-1 text-xl font-black tracking-tight text-foreground">
                  Service areas
                </h2>
              </div>

              <button
                type="button"
                onClick={() => setForm(emptyForm)}
                className="inline-flex h-11 items-center justify-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95"
              >
                <Plus className="h-4 w-4" />
                Add location
              </button>
            </div>
          </div>

          {errorMessage ? (
            <div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 p-4 text-sm font-bold text-red-700">
              <AlertTriangle className="h-4 w-4 shrink-0" />
              {errorMessage}
            </div>
          ) : null}

          <div className="overflow-hidden rounded-lg border border-border bg-white shadow-sm">
            <div className="grid grid-cols-[minmax(180px,1fr)_180px_110px_120px] gap-3 border-b border-border bg-slate-50 px-4 py-3 text-xs font-black uppercase tracking-[0.14em] text-muted-foreground max-lg:hidden">
              <span>Location</span>
              <span>Adjustment</span>
              <span>Status</span>
              <span className="text-right">Actions</span>
            </div>

            {isLoading ? (
              <div className="flex min-h-56 items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : locations.length === 0 ? (
              <div className="grid min-h-56 place-items-center p-6 text-center">
                <div>
                  <div className="mx-auto grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                    <MapPin className="h-6 w-6" />
                  </div>

                  <p className="mt-3 text-sm font-bold text-muted-foreground">
                    No locations added yet.
                  </p>
                </div>
              </div>
            ) : (
              <div className="divide-y divide-border">
                {locations.map((location) => (
                  <article
                    key={location.id}
                    className="grid gap-3 px-4 py-4 lg:grid-cols-[minmax(180px,1fr)_180px_110px_120px] lg:items-center"
                  >
                    <div className="min-w-0">
                      <p className="truncate text-sm font-black text-foreground">{location.name}</p>

                      <p className="mt-1 text-xs font-semibold text-muted-foreground lg:hidden">
                        {getAdjustmentLabel(location)}
                      </p>
                    </div>

                    <div className="hidden text-sm font-bold text-foreground lg:block">
                      {getAdjustmentLabel(location)}
                    </div>

                    <div>
                      <span
                        className={`inline-flex rounded-full px-2.5 py-1 text-xs font-black ${
                          location.isActive
                            ? "bg-emerald-50 text-emerald-700"
                            : "bg-slate-100 text-muted-foreground"
                        }`}
                      >
                        {location.isActive ? "Active" : "Inactive"}
                      </span>
                    </div>

                    <div className="flex justify-start gap-2 lg:justify-end">
                      <button
                        type="button"
                        onClick={() => openEditForm(location)}
                        className="grid h-9 w-9 place-items-center rounded-md border border-border text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                      >
                        <Edit3 className="h-4 w-4" />
                      </button>

                      <button
                        type="button"
                        onClick={() => setPendingDeleteLocation(location)}
                        className="grid h-9 w-9 place-items-center rounded-md border border-red-200 text-red-600 transition hover:bg-red-50"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </article>
                ))}
              </div>
            )}
          </div>
        </section>
      </AdminShell>

      {form ? (
        <div
          className={`fixed inset-0 z-[60] grid place-items-center bg-slate-950/45 px-4 ${spaceGrotesk.className}`}
        >
          <form
            onSubmit={saveLocation}
            className={`w-full max-w-xl rounded-2xl border border-border bg-white p-6 shadow-2xl ${spaceGrotesk.className}`}
          >
            <div className="flex items-start justify-between gap-4">
              <div>
                <div className="grid h-11 w-11 place-items-center rounded-xl bg-primary/10 text-primary">
                  <MapPin className="h-5 w-5" />
                </div>

                <h2 className="mt-4 text-2xl font-bold tracking-tight text-foreground">
                  {form.id ? "Edit location" : "Add location"}
                </h2>

                <p className="mt-1 text-sm text-muted-foreground">
                  Manage location pricing adjustment settings.
                </p>
              </div>

              <button
                type="button"
                onClick={() => setForm(null)}
                className="grid h-10 w-10 place-items-center rounded-xl text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="mt-6 grid gap-5">
              <label className="grid gap-2">
                <span className="text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground">
                  Location name
                </span>

                <input
                  value={form.name}
                  onChange={(event) =>
                    setForm({
                      ...form,
                      name: event.target.value,
                    })
                  }
                  className="h-12 rounded-xl border border-border px-4 text-sm font-medium outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
                  placeholder="Example: Delhi"
                  required
                />
              </label>

              <div className="grid gap-5 sm:grid-cols-2">
                <label className="grid gap-2">
                  <span className="text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground">
                    Adjustment type
                  </span>

                  <select
                    value={form.adjustmentType}
                    onChange={(event) =>
                      setForm({
                        ...form,
                        adjustmentType: event.target.value as LocationFormState["adjustmentType"],
                      })
                    }
                    className="h-12 rounded-xl border border-border px-4 text-sm font-medium outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
                    required
                  >
                    <option value="additional">Additional percentage</option>

                    <option value="discount">Discount percentage</option>
                  </select>
                </label>

                <label className="grid gap-2">
                  <span className="text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground">
                    Value %
                  </span>

                  <div className="relative">
                    <input
                      value={form.adjustmentValue}
                      onChange={(event) =>
                        setForm({
                          ...form,
                          adjustmentValue: event.target.value,
                        })
                      }
                      type="number"
                      min="0"
                      max="100"
                      step="0.01"
                      className="h-12 w-full rounded-xl border border-border px-4 pr-11 text-sm font-medium outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
                      required
                    />

                    <Percent className="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  </div>
                </label>
              </div>

              <label className="flex items-center gap-3 rounded-xl border border-border bg-slate-50 p-4">
                <input
                  checked={form.isActive}
                  onChange={(event) =>
                    setForm({
                      ...form,
                      isActive: event.target.checked,
                    })
                  }
                  type="checkbox"
                  className="h-4 w-4 accent-primary"
                />

                <span className="text-sm font-semibold text-foreground">Active for bookings</span>
              </label>
            </div>

            <div className="mt-7 flex justify-end gap-3">
              <button
                type="button"
                onClick={() => setForm(null)}
                className="h-11 rounded-xl border border-border px-5 text-sm font-bold text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
              >
                Cancel
              </button>

              <button
                type="submit"
                disabled={isSaving}
                className="inline-flex h-11 items-center gap-2 rounded-xl bg-primary px-5 text-sm font-bold text-primary-foreground transition hover:opacity-95 disabled:cursor-not-allowed disabled:opacity-60"
              >
                {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                Save location
              </button>
            </div>
          </form>
        </div>
      ) : null}

      {pendingDeleteLocation ? (
        <div
          className={`fixed inset-0 z-[70] grid place-items-center bg-slate-950/45 px-4 ${spaceGrotesk.className}`}
        >
          <div className="w-full max-w-sm rounded-2xl border border-border bg-white p-6 shadow-2xl">
            <div className="grid h-12 w-12 place-items-center rounded-xl bg-red-50 text-red-600">
              <Trash2 className="h-5 w-5" />
            </div>

            <h2 className="mt-4 text-2xl font-bold tracking-tight text-foreground">
              Delete location?
            </h2>

            <p className="mt-2 text-sm leading-6 text-muted-foreground">
              This will remove{" "}
              <span className="font-semibold text-foreground">{pendingDeleteLocation.name}</span>{" "}
              from admin pricing locations.
            </p>

            <div className="mt-6 flex justify-end gap-3">
              <button
                type="button"
                onClick={() => setPendingDeleteLocation(null)}
                className="h-11 rounded-xl border border-border px-5 text-sm font-bold text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
              >
                Cancel
              </button>

              <button
                type="button"
                onClick={() => deleteLocation(pendingDeleteLocation)}
                disabled={isDeletingId === pendingDeleteLocation.id}
                className="inline-flex h-11 items-center gap-2 rounded-xl bg-red-600 px-5 text-sm font-bold text-white transition hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-60"
              >
                {isDeletingId === pendingDeleteLocation.id ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : null}
                Delete
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </AdminGuard>
  );
}
