"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { MessageCircle, Plus, QrCode, RefreshCw, X } from "lucide-react";
import { toast } from "react-hot-toast";
import { EmptyState, Panel } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import { Button } from "@/components/ui/button";
import { dateTime } from "@/lib/format";
import { createWhatsAppSession, fetchWhatsAppSessions } from "./client-api";
import type { WhatsAppSession } from "./types";

function statusTone(session: WhatsAppSession) {
  const status = session.status.toLowerCase();
  if (session.connected || status === "connected") return "success" as const;
  if (["expired", "failed", "error"].some((part) => status.includes(part))) {
    return "danger" as const;
  }
  if (["connecting", "pending", "created"].some((part) => status.includes(part))) {
    return "warning" as const;
  }
  return "neutral" as const;
}

function displayStatus(session: WhatsAppSession) {
  if (session.connected) return "Connected";
  return session.status
    .split(/[_\s-]+/)
    .filter(Boolean)
    .map((part) => part[0]?.toUpperCase() + part.slice(1))
    .join(" ");
}

export function WhatsAppSessionsPanel() {
  const [sessions, setSessions] = useState<WhatsAppSession[]>([]);
  const [pairingSession, setPairingSession] = useState<WhatsAppSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshVersion, setRefreshVersion] = useState(0);
  const [error, setError] = useState("");
  const [creating, setCreating] = useState(false);

  useEffect(() => {
    const controller = new AbortController();
    void fetchWhatsAppSessions(controller.signal)
      .then((result) => {
        if (controller.signal.aborted) return;
        setSessions(result);
        setError("");
      })
      .catch((fetchError: unknown) => {
        if (!controller.signal.aborted) {
          setError(
            fetchError instanceof Error && fetchError.message.trim()
              ? fetchError.message
              : "Unable to load WhatsApp sessions. Please try again.",
          );
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false);
      });
    return () => controller.abort();
  }, [refreshVersion]);

  function refreshSessions() {
    setLoading(true);
    setError("");
    setRefreshVersion((version) => version + 1);
  }

  async function handleCreateSession() {
    setCreating(true);
    try {
      const result = await createWhatsAppSession();
      setSessions((current) => [
        result.session,
        ...current.filter((session) => session.id !== result.session.id),
      ]);
      setPairingSession(result.session.qrCode ? result.session : null);
      toast.success(result.message);
    } catch (createError) {
      toast.error(
        createError instanceof Error && createError.message.trim()
          ? createError.message
          : "Unable to create a WhatsApp session. Please try again.",
      );
    } finally {
      setCreating(false);
    }
  }

  return (
    <Panel
      title="WhatsApp Sessions"
      description="View tenant WhatsApp connections or start a new pairing session."
      actions={
        <div className="flex flex-wrap gap-2">
          <Button
            type="button"
            variant="outline"
            size="icon"
            aria-label="Refresh WhatsApp sessions"
            title="Refresh WhatsApp sessions"
            disabled={loading}
            onClick={refreshSessions}
          >
            <RefreshCw className={loading ? "size-4 animate-spin" : "size-4"} />
          </Button>
          <Button type="button" onClick={handleCreateSession} disabled={creating}>
            <Plus className={creating ? "size-4 animate-pulse" : "size-4"} aria-hidden="true" />
            {creating ? "Creating…" : "Create session"}
          </Button>
        </div>
      }
    >
      <div className="mb-5 flex items-start gap-3 rounded-xl border border-primary/20 bg-primary/5 px-4 py-3 text-sm">
        <MessageCircle className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
        <p className="text-muted-foreground">
          Creating a session starts WhatsApp pairing. Scan the QR code returned by the
          service to connect the device.
        </p>
      </div>

      {pairingSession?.qrCode && !pairingSession.connected && (
        <div className="mb-5 flex flex-col gap-4 rounded-xl border border-border bg-muted/30 p-4 sm:flex-row sm:items-center">
          <div className="flex size-56 shrink-0 items-center justify-center rounded-lg bg-white p-2">
            <Image
              src={pairingSession.qrCode}
              alt="WhatsApp pairing QR code"
              width={224}
              height={224}
              unoptimized
              className="size-full object-contain"
            />
          </div>
          <div className="min-w-0 flex-1">
            <div className="flex items-start justify-between gap-3">
              <div>
                <h3 className="font-semibold">Scan to connect WhatsApp</h3>
                <p className="mt-1 text-sm text-muted-foreground">
                  Open WhatsApp on the device and scan this temporary QR code.
                </p>
              </div>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                aria-label="Hide pairing QR code"
                onClick={() => setPairingSession(null)}
              >
                <X className="size-4" />
              </Button>
            </div>
            <p className="mt-4 text-sm text-muted-foreground">
              Session: <span className="font-medium text-foreground">{pairingSession.deviceName}</span>
            </p>
            <p className="mt-1 text-xs text-muted-foreground">
              The QR code may expire. Create a new session if pairing does not complete.
            </p>
          </div>
        </div>
      )}

      {error && (
        <div
          role="alert"
          className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive"
        >
          <span>{error}</span>
          <Button type="button" variant="outline" size="sm" onClick={refreshSessions}>
            Retry
          </Button>
        </div>
      )}

      <div className="overflow-x-auto">
        <table className="data-table min-w-[780px]">
          <thead>
            <tr>
              <th scope="col">Device</th>
              <th scope="col">WhatsApp account</th>
              <th scope="col">Status</th>
              <th scope="col">Last connected</th>
              <th scope="col">Created</th>
            </tr>
          </thead>
          <tbody>
            {loading && !sessions.length ? (
              <tr>
                <td colSpan={5} className="py-12 text-center text-muted-foreground">
                  Loading WhatsApp sessions…
                </td>
              </tr>
            ) : sessions.length ? (
              sessions.map((session) => (
                <tr key={session.id}>
                  <td className="font-medium">{session.deviceName}</td>
                  <td className="text-muted-foreground">
                    {session.phone || session.jid || "—"}
                  </td>
                  <td>
                    <StatusBadge tone={statusTone(session)}>
                      {displayStatus(session)}
                    </StatusBadge>
                  </td>
                  <td className="whitespace-nowrap text-muted-foreground">
                    {session.lastConnectedAt ? dateTime(session.lastConnectedAt) : "—"}
                  </td>
                  <td className="whitespace-nowrap text-muted-foreground">
                    {dateTime(session.createdAt)}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={5}>
                  <EmptyState
                    title={error ? "WhatsApp sessions are unavailable" : "No WhatsApp sessions"}
                    description={
                      error
                        ? "Retry the request to load the tenant's sessions."
                        : "Create a session to begin connecting a WhatsApp device."
                    }
                  />
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="mt-4 flex items-center justify-between border-t border-border pt-4 text-sm text-muted-foreground">
        <span>{sessions.length} {sessions.length === 1 ? "session" : "sessions"}</span>
        {loading && sessions.length > 0 && (
          <span className="inline-flex items-center gap-2">
            <QrCode className="size-4" aria-hidden="true" /> Updating…
          </span>
        )}
      </div>
    </Panel>
  );
}
