import { Download, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

/**
 * BankStatementDocumentTable — WealthX DS (L3 Organism)
 *
 * A table for managing bank statement documents inside the Bank Statement tab
 * of `OpportunityDetailsDrawer`. Renders two instances per opportunity:
 * one for the main applicant and one for the co-applicant.
 *
 * Features:
 *   - Select-all / individual row checkboxes
 *   - "Download All" bulk action (disabled when nothing selected)
 *   - Per-row view (click name), download, and delete actions
 *   - Loading and empty states
 *
 * Layer: L3 Organism
 *
 * Data source: bank statement documents fetched via `DocumentTypeFilter.GENERATED`
 */

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface BankStatementDocument {
  id: string;
  /** Display filename shown in the Name column. */
  name: string;
  /** Document type label, e.g. "Bank Statement" or "Property Report". */
  type: string;
  /** ISO date string or pre-formatted date label. */
  updatedDate: string;
  /** When true, download / delete action buttons are shown for this row. */
  hasDownload: boolean;
  /**
   * Whether the underlying PDF data is ready to view/download.
   * `false` or `undefined` → action buttons are shown but disabled.
   * `true` → clicking the name triggers `onView`; action buttons are enabled.
   */
  statementReady?: boolean;
}

export interface BankStatementDocumentTableProps {
  /** Section heading rendered above the table (e.g. "Main Applicant"). */
  title: string;
  documents: BankStatementDocument[];
  /** IDs of currently selected rows. */
  selectedIds: string[];
  /** Toggle a single row's selection. */
  onToggle: (id: string) => void;
  /** Toggle all rows (select all / deselect all). */
  onToggleAll: () => void;
  /** Bulk download — only enabled when `selectedIds.length > 0`. */
  onDownloadAll: () => void;
  /** Open the PDF viewer for this document (requires `statementReady`). */
  onView: (doc: BankStatementDocument) => void;
  /** Download a single document (requires `statementReady`). */
  onDownload: (doc: BankStatementDocument) => void;
  /** Open the delete confirmation for a document (requires `statementReady`). */
  onDelete: (doc: BankStatementDocument) => void;
  /** Show a loading row instead of documents. */
  isLoading?: boolean;
  /** Disable delete buttons while a deletion is in flight. */
  isDeleting?: boolean;
  className?: string;
}

// ---------------------------------------------------------------------------
// BankStatementDocumentTable
// ---------------------------------------------------------------------------

export function BankStatementDocumentTable({
  title,
  documents,
  selectedIds,
  onToggle,
  onToggleAll,
  onDownloadAll,
  onView,
  onDownload,
  onDelete,
  isLoading = false,
  isDeleting = false,
  className,
}: BankStatementDocumentTableProps) {
  const areAllSelected =
    documents.length > 0 && selectedIds.length === documents.length;
  const isIndeterminate = selectedIds.length > 0 && !areAllSelected;

  return (
    <div
      className={cn("flex flex-col gap-2", className)}
      data-slot="bank-statement-document-table"
    >
      {/* ── Header ── */}
      <div className="flex items-center justify-between">
        <p className="text-body-large font-semibold">{title}</p>
        <Button
          variant="outline"
          size="sm"
          onClick={onDownloadAll}
          disabled={selectedIds.length === 0}
        >
          Download All
        </Button>
      </div>

      {/* ── Table ── */}
      <Table className="table-fixed">
        <TableHeader>
          <TableRow>
            <TableHead className="w-10">
              <Checkbox
                checked={areAllSelected}
                indeterminate={isIndeterminate}
                onCheckedChange={onToggleAll}
                aria-label="Select all"
                disabled={isLoading || documents.length === 0}
              />
            </TableHead>
            <TableHead>Name</TableHead>
            <TableHead className="w-36">Type</TableHead>
            <TableHead className="w-32">Date</TableHead>
            <TableHead className="w-20">Action</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {isLoading ? (
            <TableRow>
              <TableCell colSpan={5} className="py-8 text-center">
                <p className="text-body-medium text-muted-foreground">
                  Loading documents…
                </p>
              </TableCell>
            </TableRow>
          ) : documents.length === 0 ? (
            <TableRow>
              <TableCell colSpan={5} className="py-8 text-center">
                <p className="text-body-medium text-muted-foreground">
                  No documents found
                </p>
              </TableCell>
            </TableRow>
          ) : (
            documents.map((doc) => (
              <TableRow key={doc.id}>
                <TableCell>
                  <Checkbox
                    checked={selectedIds.includes(doc.id)}
                    onCheckedChange={() => onToggle(doc.id)}
                    aria-label={`Select ${doc.name}`}
                  />
                </TableCell>

                {/* Name — clickable when download is ready */}
                <TableCell>
                  <p
                    className={cn(
                      "truncate text-body-medium font-semibold text-foreground",
                      doc.hasDownload && doc.statementReady
                        ? "cursor-pointer hover:underline"
                        : "cursor-default",
                    )}
                    onClick={() => {
                      if (doc.hasDownload && doc.statementReady) {
                        onView(doc);
                      }
                    }}
                  >
                    {doc.name}
                  </p>
                </TableCell>

                <TableCell>
                  <span className="truncate text-body-medium">{doc.type}</span>
                </TableCell>
                <TableCell>
                  <span className="truncate text-body-medium">
                    {doc.updatedDate}
                  </span>
                </TableCell>

                {/* Actions */}
                <TableCell>
                  <div className="flex gap-1">
                    {doc.hasDownload && (
                      <>
                        <Button
                          variant="ghost"
                          size="icon-sm"
                          aria-label="Download"
                          onClick={() => onDownload(doc)}
                          disabled={!doc.statementReady}
                        >
                          <Download className="size-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon-sm"
                          aria-label="Delete"
                          onClick={() => onDelete(doc)}
                          disabled={!doc.statementReady || isDeleting}
                        >
                          <Trash2 className="size-4" />
                        </Button>
                      </>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </div>
  );
}
