"use client";

import { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown, CheckCircle2, AlertCircle, FileX, Upload, Package } from "lucide-react";
import type { ClassifiedDeal, DocStatusMap, DocStatus } from "./types";

function SortableHeader({
  label,
  column,
}: {
  label: string;
  column: { toggleSorting: (desc: boolean) => void; getIsSorted: () => false | "asc" | "desc" };
}) {
  return (
    <button
      className="flex items-center gap-1 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-brandblue transition-colors group"
      onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
    >
      {label}
      <ArrowUpDown className="h-3 w-3 opacity-40 group-hover:opacity-70 transition-opacity" />
    </button>
  );
}

function RetroAssessmentBadge({ status }: { status: DocStatus | undefined }) {
  if (status?.isSurveyComplete) {
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-emerald-50 text-emerald-700 border-emerald-200">
        <CheckCircle2 className="h-3.5 w-3.5" />
        Complete
      </span>
    );
  }
  if (status?.hasSurveyDocs) {
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-amber-50 text-amber-700 border-amber-200">
        <AlertCircle className="h-3.5 w-3.5" />
        Partial
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-gray-50 text-gray-400 border-gray-200">
      <FileX className="h-3.5 w-3.5" />
      No Docs
    </span>
  );
}

function InstallDocsBadge({ status }: { status: DocStatus | undefined }) {
  const installStatus = status?.installStatus ?? "none";
  const measureProgress = status?.measureProgress ?? [];

  // Build a tooltip showing per-measure doc counts (e.g. "ASHP: 5/9, CWI: 7/7")
  const tooltip =
    measureProgress.length > 0
      ? measureProgress
          .map((m) => `${m.measureName}: ${m.uploadedCount}/${m.requiredCount}`)
          .join(" | ")
      : undefined;

  if (installStatus === "all") {
    return (
      <span
        title={tooltip}
        className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-emerald-50 text-emerald-700 border-emerald-200"
      >
        <CheckCircle2 className="h-3.5 w-3.5" />
        All Measures
      </span>
    );
  }
  if (installStatus === "partial") {
    const completedCount = measureProgress.filter((m) => m.isComplete).length;
    const totalCount = measureProgress.length;
    const label = totalCount > 0 ? `${completedCount} / ${totalCount} measures` : "Some Measures";
    return (
      <span
        title={tooltip}
        className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-amber-50 text-amber-700 border-amber-200"
      >
        <AlertCircle className="h-3.5 w-3.5" />
        {label}
      </span>
    );
  }
  if (installStatus === "hasDocs") {
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-sky-50 text-sky-700 border-sky-200">
        <Package className="h-3.5 w-3.5" />
        Has Docs
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap bg-gray-50 text-gray-400 border-gray-200">
      <FileX className="h-3.5 w-3.5" />
      No Docs
    </span>
  );
}

export function createDocumentTableColumns(
  onOpenDrawer: (dealId: string, uprn: string | null, landlordPropertyId: string | null, dealname: string | null) => void,
  docStatusMap: DocStatusMap = {},
  onUpload?: (deal: ClassifiedDeal) => void,
): ColumnDef<ClassifiedDeal>[] {
  return [
    // ── Address ──────────────────────────────────────────────────────────
    {
      accessorKey: "dealname",
      id: "dealname",
      header: ({ column }) => <SortableHeader label="Address" column={column as any} />,
      cell: ({ row }) => (
        <div className="max-w-[260px]">
          <p className="text-sm font-medium text-gray-900 leading-tight truncate">
            {row.original.dealname ?? "—"}
          </p>
        </div>
      ),
      enableHiding: false,
    },

    // ── Landlord ID ──────────────────────────────────────────────────────
    {
      accessorKey: "landlordPropertyId",
      id: "landlordPropertyId",
      header: ({ column }) => <SortableHeader label="Landlord ID" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs font-mono text-gray-500">
          {row.original.landlordPropertyId ?? "—"}
        </span>
      ),
      enableHiding: false,
    },

    // ── Retrofit Assessment Docs Status ───────────────────────────────────
    {
      id: "retroAssessmentStatus",
      accessorFn: (row) => {
        const status = docStatusMap[row.dealId];
        if (status?.isSurveyComplete) return 2;
        if (status?.hasSurveyDocs) return 1;
        return 0;
      },
      header: ({ column }) => <SortableHeader label="Retrofit Assessment Docs" column={column as any} />,
      cell: ({ row }) => {
        const status = docStatusMap[row.original.dealId];
        return <RetroAssessmentBadge status={status} />;
      },
      enableHiding: false,
    },

    // ── Install Docs Status ───────────────────────────────────────────────
    {
      id: "installDocs",
      accessorFn: (row) => {
        const status = docStatusMap[row.dealId];
        const s = status?.installStatus ?? "none";
        if (s === "all") return 3;
        if (s === "partial") return 2;
        if (s === "hasDocs") return 1;
        return 0;
      },
      header: ({ column }) => <SortableHeader label="Install Docs" column={column as any} />,
      cell: ({ row }) => {
        const status = docStatusMap[row.original.dealId];
        return <InstallDocsBadge status={status} />;
      },
      enableHiding: false,
    },

    // ── Documents button ─────────────────────────────────────────────────
    {
      id: "documents",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">Docs</span>
      ),
      cell: ({ row }) => {
        const status = docStatusMap[row.original.dealId];

        let icon: React.ReactNode;
        let className: string;

        if (status?.isSurveyComplete) {
          icon = <CheckCircle2 className="h-3.5 w-3.5" />;
          className =
            "inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-emerald-200 text-emerald-700 bg-emerald-50 hover:bg-emerald-100 hover:border-emerald-300 transition-all duration-150 whitespace-nowrap";
        } else if (status?.hasSurveyDocs) {
          icon = <AlertCircle className="h-3.5 w-3.5" />;
          className =
            "inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-amber-200 text-amber-700 bg-amber-50 hover:bg-amber-100 hover:border-amber-300 transition-all duration-150 whitespace-nowrap";
        } else {
          icon = <FileX className="h-3.5 w-3.5" />;
          className =
            "inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-gray-200 text-gray-400 bg-gray-50 hover:bg-gray-100 hover:border-gray-300 transition-all duration-150 whitespace-nowrap";
        }

        return (
          <button
            onClick={() =>
              onOpenDrawer(
                row.original.dealId,
                row.original.uprn,
                row.original.landlordPropertyId,
                row.original.dealname,
              )
            }
            className={className}
          >
            {icon}
            Docs
          </button>
        );
      },
      enableSorting: false,
      enableHiding: false,
    },

    // ── Upload button (contractor only) ──────────────────────────────────
    ...(onUpload ? [{
      id: "upload",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">Upload</span>
      ),
      cell: ({ row }: { row: { original: ClassifiedDeal } }) => (
        <button
          onClick={() => onUpload(row.original)}
          className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-brandblue/20 text-brandblue bg-brandlightblue/20 hover:bg-brandlightblue/40 hover:border-brandblue/40 transition-all duration-150 whitespace-nowrap"
        >
          <Upload className="h-3.5 w-3.5" />
          Upload Docs
        </button>
      ),
      enableSorting: false,
      enableHiding: false,
    } as ColumnDef<ClassifiedDeal>] : []),
  ];
}
