"use client";

import Link from "next/link";
import { Archive, FileEdit, Inbox, Link2Off, Mails, Pause, Pencil, RefreshCw, Send, SendHorizontal, Star, TriangleAlert } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { timeAgo } from "./mail-shared";

// Left pane: mailbox switcher, folders with counts, Compose, and sync health.

const ALL = "__all__";

export const FOLDER_ITEMS = [
  { key: "inbox", label: "Inbox", icon: Inbox, count: (folders) => folders?.inbox?.unread, countTitle: (n) => `${n} unread` },
  { key: "unlinked", label: "Needs linking", icon: Link2Off, count: (folders) => folders?.unlinked?.total, countTitle: (n) => `${n} conversations not linked to a buyer, factory or order`, tone: "warning" },
  { key: "starred", label: "Starred", icon: Star, count: (folders) => folders?.starred?.total, quiet: true },
  { key: "sent", label: "Sent", icon: Send },
  { key: "drafts", label: "Drafts", icon: FileEdit, count: (folders) => folders?.drafts?.total, quiet: true },
  { key: "outbox", label: "Outbox", icon: SendHorizontal, count: (folders) => (folders?.outbox?.queued || 0) + (folders?.outbox?.failed || 0), countTitle: (n, folders) => (folders?.outbox?.failed ? `${folders.outbox.failed} failed to send` : `${n} waiting to send`), tone: (folders) => (folders?.outbox?.failed ? "danger" : null) },
  { key: "archived", label: "Archived", icon: Archive },
  // Everything, including sent-only threads and mail marked "not business mail" (so that can be undone later).
  { key: "all", label: "All mail", icon: Mails },
];

export const folderLabel = (key) => FOLDER_ITEMS.find((item) => item.key === key)?.label || "Inbox";

const SYNC_TONES = { ok: "bg-success", error: "bg-destructive", auth_failed: "bg-destructive", never: "bg-muted-foreground/50" };
const SYNC_LABELS = { ok: "Syncing normally", error: "Connection problem", auth_failed: "Sign-in failed", never: "Not synced yet" };

function SyncDot({ account }) {
  // Paused mailboxes get the quiet "not syncing" dot, not the error one.
  const status = account?.status === "active" ? account?.sync?.status || "never" : account?.status === "paused" ? "never" : "error";
  return <span className="flex items-center"><span className={cn("size-2 shrink-0 rounded-full", SYNC_TONES[status] || SYNC_TONES.never)} aria-hidden="true" /><span className="sr-only">{account?.status === "active" ? SYNC_LABELS[status] : `Mailbox ${account?.status}`}</span></span>;
}

export function FolderPane({ state, summary, isLoading, onSelectFolder, onSelectAccount, canCompose, onCompose, onSync, isSyncing, onResume, isResuming, footer, className }) {
  const accounts = summary?.accounts || [];
  const folders = summary?.folders;
  const current = accounts.find((account) => String(account.id) === String(state.account)) || null;
  const scope = current ? [current] : accounts;
  const broken = scope.filter((account) => account.status === "error" || ["error", "auth_failed"].includes(account.sync?.status));
  const paused = scope.filter((account) => account.status === "paused");
  // Send-only mailboxes (no IMAP) have nothing to sync: they get a plain note instead of "Not synced yet · Sync now".
  const syncable = scope.filter((account) => account.status !== "paused" && account.imap?.enabled !== false);
  const sendOnly = scope.filter((account) => account.status !== "paused" && account.imap?.enabled === false);
  const oldestSync = syncable.map((account) => account.sync?.lastSyncedAt).filter(Boolean).sort()[0];

  return <nav aria-label="Mail folders" className={cn("flex min-h-0 flex-col gap-3", className)}>
    {canCompose && <Button className="w-full justify-start" onClick={onCompose}><Pencil /> Compose</Button>}

    {isLoading && !summary ? <Skeleton className="h-9 w-full" /> : accounts.length > 1 && <Select value={state.account || ALL} onValueChange={(value) => onSelectAccount(value === ALL ? "" : value)}>
      <SelectTrigger className="w-full" aria-label="Mailbox">
        <SelectValue>{current ? <span className="flex min-w-0 items-center gap-2"><SyncDot account={current} /><span className="truncate">{current.name}</span></span> : "All mailboxes"}</SelectValue>
      </SelectTrigger>
      <SelectContent>
        <SelectItem value={ALL}>All mailboxes</SelectItem>
        {accounts.map((account) => <SelectItem key={account.id} value={String(account.id)}>
          <span className="flex min-w-0 items-center gap-2"><SyncDot account={account} /><span className="grid min-w-0"><span className="truncate">{account.name}</span><span className="truncate text-xs text-muted-foreground">{account.emailAddress}</span></span></span>
        </SelectItem>)}
      </SelectContent>
    </Select>}
    {accounts.length === 1 && <div className="flex min-w-0 items-center gap-2 px-1 text-sm"><SyncDot account={accounts[0]} /><span className="grid min-w-0"><span className="truncate font-medium">{accounts[0].name}</span><span className="truncate text-xs text-muted-foreground">{accounts[0].emailAddress}</span></span></div>}

    <ul className="grid gap-0.5">
      {FOLDER_ITEMS.map((item) => {
        const count = item.count?.(folders) || 0;
        const tone = typeof item.tone === "function" ? item.tone(folders) : item.tone;
        const active = state.folder === item.key;
        return <li key={item.key}>
          <button
            type="button"
            onClick={() => onSelectFolder(item.key)}
            aria-current={active ? "page" : undefined}
            className={cn(
              "flex h-9 w-full items-center gap-2.5 rounded-md px-2.5 text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
              active ? "bg-accent font-medium text-accent-foreground" : "text-foreground/85",
            )}
          >
            <item.icon className={cn("size-4 shrink-0", active ? "text-foreground" : "text-muted-foreground")} />
            <span className="flex-1 truncate text-left">{item.label}</span>
            {count > 0 && <Badge
              variant={tone === "danger" ? "danger" : tone === "warning" ? "warning" : "secondary"}
              className={cn("h-5 min-w-5 px-1.5 tabular-nums", item.quiet && "bg-transparent font-normal text-muted-foreground")}
              title={item.countTitle?.(count, folders)}
            >{count > 99 ? "99+" : count}{tone === "danger" && <span className="sr-only"> failed</span>}</Badge>}
          </button>
        </li>;
      })}
    </ul>

    <div className="mt-auto grid gap-2 border-t pt-3 text-xs text-muted-foreground">
      {broken.length > 0 && <div className="flex items-start gap-2 rounded-md bg-destructive/10 p-2 text-destructive" role="alert">
        <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />
        <span>{broken.length === 1 ? `${broken[0].name}: mailbox error.` : `${broken.length} mailboxes have errors.`} <Link href="/settings/email-accounts" className="font-medium underline underline-offset-2">Fix in settings</Link></span>
      </div>}
      {paused.map((account) => <div key={account.id} className="flex min-w-0 items-center gap-1.5" title={`${account.emailAddress} is paused: nothing is synced or sent. Queued emails wait until it is resumed.`}>
        <Pause className="size-3.5 shrink-0" aria-hidden="true" />
        <span className="truncate">{scope.length > 1 ? `${account.name}: paused` : "Paused"}</span>
        {account.canManage && onResume && <>
          <span aria-hidden="true">·</span>
          <Button variant="link" size="xs" className="h-auto shrink-0 p-0 text-xs" onClick={() => onResume(account)} disabled={isResuming?.(account)} aria-label={`Resume ${account.emailAddress}`}>{isResuming?.(account) && <Spinner />}Resume</Button>
        </>}
      </div>)}
      {sendOnly.length > 0 && <div className="truncate" title="This mailbox only sends: its inbox is not read. Turn on IMAP in the mailbox settings to see replies here.">{scope.length > 1 ? `${sendOnly.map((account) => account.name).join(", ")}: send only` : "Send only · replies are not synced"}</div>}
      {syncable.length > 0 && <div className="flex items-center justify-between gap-2">
        <span className="truncate" title={oldestSync ? new Date(oldestSync).toLocaleString() : undefined}>{oldestSync ? `Synced ${timeAgo(oldestSync)}` : "Not synced yet"}</span>
        <Button variant="ghost" size="xs" className="shrink-0" onClick={() => onSync(syncable)} disabled={isSyncing}>{isSyncing ? <Spinner /> : <RefreshCw />} Sync now</Button>
      </div>}
      {footer}
    </div>
  </nav>;
}
