"use client";

import { useState } from "react";
import { MessageCircle, Plus } from "lucide-react";
import { Button, EmptyState, PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useSession } from "@/components/session";
import { ConnectDialog } from "@/components/whatsapp/connect-dialog";
import { NumberPanel } from "@/components/whatsapp/number-panel";
import { formatDate } from "@/lib/format";
import { useApi } from "@/lib/use-api";
import type { WhatsAppAccount, WhatsAppConfig } from "@/lib/types";

type DialogState = { mode: "connect"; prefill?: { waba_id: string; phone_number_id: string } } | { mode: "rotate"; account: WhatsAppAccount } | null;

export default function WhatsAppSetupPage() {
  const { can } = useSession();
  const canManage = can("whatsapp.manage");
  const accounts = useApi<{ data: WhatsAppAccount[] }>("/whatsapp/accounts");
  const configReq = useApi<{ data: WhatsAppConfig }>("/whatsapp/config");
  const config = configReq.data?.data ?? null;
  const [dialog, setDialog] = useState<DialogState>(null);

  const all = accounts.data?.data;
  const active = all?.filter((a) => a.status !== "disconnected") ?? [];
  const disconnected = all?.filter((a) => a.status === "disconnected") ?? [];

  return (
    <>
      <PageHeader
        title="WhatsApp setup"
        description="Connect the WhatsApp Business numbers you message customers from. Devwebs uses Meta's official Cloud API."
        actions={
          canManage &&
          active.length > 0 && (
            <Button icon={<Plus className="size-4" />} onClick={() => setDialog({ mode: "connect" })}>
              Add another number
            </Button>
          )
        }
      />

      {config?.mode === "simulation" && (
        <div className="mb-6 rounded-lg border border-amber/30 bg-amber-soft px-4 py-3 text-sm text-amber">
          <span className="font-semibold">Simulation mode.</span> Nothing is sent to Meta and no real phone receives messages. Set <code>WHATSAPP_PROVIDER=cloud</code> on the server to go live.
        </div>
      )}

      {accounts.error && <p className="mb-4 rounded-md bg-brick-soft px-3 py-2 text-sm text-brick">{accounts.error}</p>}

      {!all ? (
        <Panel className="space-y-3 p-5">
          <Skeleton className="h-7 w-56" />
          <Skeleton className="h-4 w-96" />
          <Skeleton className="h-40 w-full" />
        </Panel>
      ) : active.length === 0 ? (
        <Panel>
          <EmptyState
            icon={<MessageCircle className="size-5" />}
            title="No WhatsApp number connected yet"
            body={
              canManage
                ? "Connect a number from your Meta Business account to receive messages here, send campaigns and run bots."
                : "Ask a workspace owner to connect your business's WhatsApp number."
            }
            action={
              canManage && (
                <Button variant="primary" onClick={() => setDialog({ mode: "connect" })}>
                  Connect a number
                </Button>
              )
            }
          />
        </Panel>
      ) : (
        <div className="space-y-6">
          {active.map((a) => (
            <NumberPanel
              key={a.id}
              account={a}
              config={config}
              canManage={canManage}
              showDefaultControls={active.length > 1}
              onChanged={accounts.reload}
              onRotate={() => setDialog({ mode: "rotate", account: a })}
            />
          ))}
        </div>
      )}

      {disconnected.length > 0 && (
        <section className="mt-8">
          <h2 className="mb-2 text-sm font-semibold text-muted">Previously connected</h2>
          <Panel>
            <ul className="divide-y divide-line">
              {disconnected.map((a) => (
                <li key={a.id} className="flex flex-wrap items-center gap-3 px-4 py-3 text-sm">
                  <span className="tabular font-medium">{a.display_phone_number ?? a.phone_number_id}</span>
                  <span className="text-muted">{a.verified_name}</span>
                  <span className="flex-1 text-muted">Disconnected {formatDate(a.disconnected_at)}</span>
                  {canManage && (
                    <Button size="sm" onClick={() => setDialog({ mode: "connect", prefill: { waba_id: a.waba_id, phone_number_id: a.phone_number_id } })}>
                      Reconnect
                    </Button>
                  )}
                </li>
              ))}
            </ul>
          </Panel>
        </section>
      )}

      {dialog && (
        <ConnectDialog
          account={dialog.mode === "rotate" ? dialog.account : undefined}
          prefill={dialog.mode === "connect" ? dialog.prefill : undefined}
          config={config}
          onClose={() => setDialog(null)}
          onDone={() => {
            setDialog(null);
            accounts.reload();
          }}
        />
      )}
    </>
  );
}
