import Link from "next/link";
import { updateInquiryStatusAction, deleteInquiryAction } from "@/app/dashboard/actions";
import { DashboardPageHeader } from "@/components/dashboard/page-header";
import {
  EmptyState,
  PrimaryButton,
} from "@/components/dashboard/empty-state";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import {
  listInquiries,
  type InquiryStatus,
} from "@/services/inquiry-service";

const STATUSES: InquiryStatus[] = [
  "new",
  "qualified",
  "consultation",
  "proposal",
  "won",
  "lost",
];

function statusTone(status: InquiryStatus) {
  if (status === "new") return "bg-[var(--archi-gold)]/15 text-[#8a7010]";
  if (status === "won") return "bg-emerald-500/15 text-emerald-800";
  if (status === "lost") return "bg-red-500/10 text-red-800";
  return "bg-[var(--archi-ink)]/8 text-[var(--archi-ink-muted)]";
}

export default async function DashboardInquiriesPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  const { status: statusFilter } = await searchParams;
  const ctx = await requireDashboardContext("inquiries:manage");
  const rows = await listInquiries(ctx.tenant);
  const filtered =
    statusFilter && STATUSES.includes(statusFilter as InquiryStatus)
      ? rows.filter((row) => row.status === statusFilter)
      : rows;

  const counts = STATUSES.reduce(
    (acc, status) => {
      acc[status] = rows.filter((row) => row.status === status).length;
      return acc;
    },
    {} as Record<InquiryStatus, number>,
  );

  return (
    <DashboardShell width="wide">
      <DashboardPageHeader
        eyebrow="Studio"
        title="Inquiries"
        description={`Leads submitted to ${ctx.tenant.studioName}. Update status as you qualify and close work.`}
      />

      <div className="mt-8 flex flex-wrap gap-2">
        <FilterChip
          href="/dashboard/inquiries"
          label="All"
          count={rows.length}
          active={!statusFilter}
        />
        {STATUSES.map((status) => (
          <FilterChip
            key={status}
            href={`/dashboard/inquiries?status=${status}`}
            label={status}
            count={counts[status]}
            active={statusFilter === status}
          />
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="mt-10">
          <EmptyState
            title={rows.length === 0 ? "No inquiries yet" : "No matches"}
            description={
              rows.length === 0
                ? "When visitors contact your public site, leads appear here for review."
                : "Try another status filter to see more leads."
            }
            action={
              rows.length === 0 ? (
                <PrimaryButton href="/dashboard/settings">
                  Review studio profile
                </PrimaryButton>
              ) : (
                <Link
                  href="/dashboard/inquiries"
                  className="text-sm text-[var(--archi-gold)] underline"
                >
                  Clear filter
                </Link>
              )
            }
          />
        </div>
      ) : (
        <ul className="mt-8 space-y-4">
          {filtered.map((inquiry) => (
            <li
              key={inquiry.id}
              className="rounded-2xl border border-[var(--archi-line)] bg-white/80 p-5"
            >
              <div className="flex flex-wrap items-start justify-between gap-4">
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <Link
                      href={`/dashboard/inquiries/${inquiry.id}`}
                      className="font-[family-name:var(--font-display)] text-2xl hover:opacity-80"
                    >
                      {inquiry.name}
                    </Link>
                    <span
                      className={`rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase ${statusTone(inquiry.status as InquiryStatus)}`}
                    >
                      {inquiry.status}
                    </span>
                  </div>
                  <p className="mt-1 text-sm text-[var(--archi-ink-muted)]">
                    {inquiry.email}
                    {inquiry.phone ? ` · ${inquiry.phone}` : ""}
                  </p>
                </div>
                <form
                  action={async (formData) => {
                    "use server";
                    const status = String(
                      formData.get("status") ?? "",
                    ) as InquiryStatus;
                    await updateInquiryStatusAction(inquiry.id, status);
                  }}
                  className="flex items-center gap-2"
                >
                  <label className="sr-only" htmlFor={`status-${inquiry.id}`}>
                    Status
                  </label>
                  <select
                    id={`status-${inquiry.id}`}
                    name="status"
                    defaultValue={inquiry.status}
                    className="rounded-lg border border-[var(--archi-line)] bg-white px-2 py-1.5 text-sm"
                  >
                    {STATUSES.map((status) => (
                      <option key={status} value={status}>
                        {status}
                      </option>
                    ))}
                  </select>
                  <button
                    type="submit"
                    className="archi-btn-primary text-xs"
                  >
                    Update
                  </button>
                </form>
                <form action={deleteInquiryAction.bind(null, inquiry.id)}>
                  <button
                    type="submit"
                    className="text-xs text-red-800 underline"
                  >
                    Delete
                  </button>
                </form>
              </div>
              <p className="mt-4 whitespace-pre-wrap text-sm leading-6">
                {inquiry.message}
              </p>
              <p className="mt-3 text-xs text-[var(--archi-ink-muted)]">
                {[inquiry.projectType, inquiry.location, inquiry.budget]
                  .filter(Boolean)
                  .join(" · ") || "No extra details"}
                {" · "}
                {inquiry.createdAt
                  ? new Date(inquiry.createdAt).toLocaleString()
                  : ""}
              </p>
            </li>
          ))}
        </ul>
      )}
    </DashboardShell>
  );
}

function FilterChip({
  href,
  label,
  count,
  active,
}: {
  href: string;
  label: string;
  count: number;
  active: boolean;
}) {
  return (
    <Link
      href={href}
      className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs tracking-wide uppercase transition ${
        active
          ? "bg-[var(--archi-ink)] text-[var(--archi-bg)]"
          : "border border-[var(--archi-line)] bg-white text-[var(--archi-ink-muted)] hover:border-[var(--archi-gold)]/40"
      }`}
    >
      {label}
      <span className={active ? "text-white/70" : "text-[var(--archi-ink-muted)]"}>
        {count}
      </span>
    </Link>
  );
}
