import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { ArrowRight, Loader2, Plus } from "lucide-react";
import { SectionCard } from "@/components/account/parts";
import { AddBusinessDialog } from "@/components/partner/AddBusinessDialog";
import { businessLabel, useBusiness } from "@/lib/business-context";

export const Route = createFileRoute("/_partner/settings/businesses")({
  head: () => ({
    meta: [
      { title: "Businesses — Airfis Partner" },
      { name: "description", content: "Manage the businesses connected to your Airfis account." },
      { property: "og:title", content: "Businesses — Airfis Partner" },
      {
        property: "og:description",
        content: "Switch, manage and add businesses on your Airfis account.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: BusinessesSettings,
});

function initials(name: string) {
  return name
    .split(/\s+/)
    .map((w) => w[0])
    .filter(Boolean)
    .slice(0, 2)
    .join("")
    .toUpperCase();
}

function BusinessesSettings() {
  const { businesses, activeId, setActiveId, isLoading } = useBusiness();
  const navigate = useNavigate();
  const [addOpen, setAddOpen] = useState(false);

  return (
    <SectionCard title="Businesses" description="Manage the businesses connected to your account.">
      {isLoading ? (
        <div className="flex justify-center py-16">
          <Loader2 className="h-5 w-5 animate-spin text-ink-3" />
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2">
          {businesses.map((b) => {
            const current = b.id === activeId;
            return (
              <div
                key={b.id}
                className={`rounded-xl border p-4 ${current ? "border-[#FF4308]" : "border-hairline"}`}
              >
                <span className="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-[#0a0a12] text-xs font-bold text-white">
                  {initials(businessLabel(b))}
                </span>
                <p className="mt-4 truncate font-bold text-ink">{businessLabel(b)}</p>
                <p className="truncate text-sm text-ink-2">
                  {[b.business_type, b.city].filter(Boolean).join(" · ")}
                </p>
                {current ? (
                  <p className="mt-3 text-xs font-semibold text-[#FF4308]">Current Business</p>
                ) : (
                  <button
                    type="button"
                    onClick={() => {
                      setActiveId(b.id);
                      navigate({ to: "/partner/dashboard" });
                    }}
                    className="mt-3 text-xs font-semibold text-ink-2 hover:text-ink"
                  >
                    Set as current
                  </button>
                )}
                <Link
                  to="/partner/account"
                  className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-ink hover:text-[#FF4308]"
                >
                  Manage Business <ArrowRight className="h-4 w-4" />
                </Link>
              </div>
            );
          })}

          <button
            type="button"
            onClick={() => setAddOpen(true)}
            className="flex min-h-[168px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-hairline text-sm font-semibold text-ink-2 transition-colors hover:border-[#FF4308] hover:text-[#FF4308]"
          >
            <Plus className="h-5 w-5" /> Add New Business
          </button>
        </div>
      )}
      <AddBusinessDialog open={addOpen} onClose={() => setAddOpen(false)} />
    </SectionCard>
  );
}
