"use client";

import { useCallback, useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { MapPin, Pencil, Plus, Star, Trash2 } from "lucide-react";
import LocationFormModal from "@/components/businesses/LocationFormModal";
import Button from "@/components/ui/Button";
import ConfirmModal from "@/components/ui/ConfirmModal";
import { useBusinessPanelAccess } from "@/hooks/useBusinessPanelAccess";

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

interface LocationRow {
  id: string;
  name: string;
  address: string | null;
  city: string | null;
  country: string | null;
  phone: string | null;
  isMain: boolean;
  isActive: boolean;
  franchiseId: string | null;
  franchise: { id: string; name: string } | null;
}

export default function BusinessPanelLocations() {
  const t = useTranslations("businessPanel");
  const tl = useTranslations("locations");
  const tc = useTranslations("common");
  const { businessId, canManageLocations } = useBusinessPanelAccess();

  const [locations, setLocations] = useState<LocationRow[]>([]);
  const [franchises, setFranchises] = useState<FranchiseOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<{ open: boolean; location: LocationRow | null }>({
    open: false,
    location: null,
  });
  const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);
  const [deleting, setDeleting] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/business-panel");
      if (!res.ok) throw new Error("Failed");
      const json = await res.json();
      setLocations(json.locations ?? []);
      setFranchises(
        (json.franchises ?? []).map((fr: { id: string; name: string }) => ({
          id: fr.id,
          name: fr.name,
        }))
      );
    } catch {
      setLocations([]);
      setFranchises([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function handleDelete(id: string) {
    if (!businessId) return;
    setDeleting(true);
    try {
      await fetch(`/api/businesses/${businessId}/locations/${id}`, { method: "DELETE" });
      setDeleteTarget(null);
      fetchData();
    } finally {
      setDeleting(false);
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h2 className="text-lg font-semibold text-[var(--text)]">{t("locationsTitle")}</h2>
          <p className="mt-1 text-sm text-[var(--text-muted)]">{t("locationsSubtitle")}</p>
        </div>
        {canManageLocations && (
          <Button onClick={() => setModal({ open: true, location: null })} className="w-full sm:w-auto">
            <Plus className="h-4 w-4" />
            {tl("addLocation")}
          </Button>
        )}
      </div>

      {loading ? (
        <p className="text-sm text-[var(--text-muted)]">{t("loading")}</p>
      ) : locations.length === 0 ? (
        <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center">
          <MapPin className="mx-auto mb-2 h-8 w-8 text-[var(--text-faint)]" />
          <p className="text-sm text-[var(--text-muted)]">{t("noLocations")}</p>
          {canManageLocations && (
            <Button
              variant="secondary"
              className="mt-4"
              onClick={() => setModal({ open: true, location: null })}
            >
              <Plus className="h-4 w-4" />
              {tl("addLocation")}
            </Button>
          )}
        </div>
      ) : (
        <div className="space-y-2">
          {locations.map((location) => (
            <div
              key={location.id}
              className="flex items-center gap-3 rounded-xl border border-[var(--border)] bg-[var(--bg)]/40 p-4"
            >
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-sky-500/10 text-sky-400">
                <MapPin className="h-4 w-4" />
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="font-medium text-[var(--text)]">{location.name}</span>
                  {location.isMain && (
                    <span className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-400">
                      <Star className="h-3 w-3" />
                      {t("mainLocation")}
                    </span>
                  )}
                  <span
                    className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${
                      location.isActive
                        ? "bg-emerald-500/10 text-emerald-400"
                        : "bg-[var(--bg-elevated)] text-[var(--text-muted)] ring-1 ring-[var(--border)]"
                    }`}
                  >
                    {location.isActive ? tc("active") : tc("inactive")}
                  </span>
                </div>
                <p className="mt-0.5 text-xs text-[var(--text-faint)]">
                  {[location.city, location.country].filter(Boolean).join(", ") || "—"}
                  {location.franchise ? ` · ${location.franchise.name}` : ""}
                </p>
              </div>
              {canManageLocations && (
                <div className="flex shrink-0 items-center gap-1">
                  <button
                    type="button"
                    onClick={() => setModal({ open: true, location })}
                    className="cursor-pointer rounded-lg p-1.5 text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"
                    aria-label={tc("edit")}
                  >
                    <Pencil className="h-3.5 w-3.5" />
                  </button>
                  <button
                    type="button"
                    onClick={() => setDeleteTarget({ id: location.id, name: location.name })}
                    className="cursor-pointer rounded-lg p-1.5 text-[var(--text-muted)] hover:bg-red-500/10 hover:text-red-500"
                    aria-label={tc("delete")}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {modal.open && businessId && (
        <LocationFormModal
          businessId={businessId}
          location={modal.location}
          franchises={franchises}
          onSave={() => {
            setModal({ open: false, location: null });
            fetchData();
          }}
          onClose={() => setModal({ open: false, location: null })}
        />
      )}

      <ConfirmModal
        open={Boolean(deleteTarget)}
        title={tc("confirmTitle")}
        description={
          deleteTarget ? `${tl("deleteConfirm")} (${deleteTarget.name})` : tc("confirmDelete")
        }
        loading={deleting}
        onConfirm={() => deleteTarget && handleDelete(deleteTarget.id)}
        onCancel={() => !deleting && setDeleteTarget(null)}
      />
    </div>
  );
}
