"use client";

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

// -----------------------------------------------------------------------
// Stage badge — consistent pill rendering
// -----------------------------------------------------------------------
function StageBadge({ stage }: { stage: DisplayStage }) {
  const c = STAGE_COLORS[stage] ?? STAGE_COLORS["Unknown Stage"];
  return (
    <span
      className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap ${c.bg} ${c.text} ${c.border}`}
    >
      <span className={`w-1.5 h-1.5 rounded-full shrink-0 ${c.dot}`} />
      {stage}
    </span>
  );
}

// Sortable column header helper
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>
  );
}

// -----------------------------------------------------------------------
// Column factory — takes onOpenDrawer so the Documents button can trigger it
// showDocuments controls whether the Docs action column is included
// docStatusMap provides per-deal document status for status indicators
// -----------------------------------------------------------------------
export function createPropertyTableColumns(
  onOpenDrawer: (dealId: string, uprn: string | null, landlordPropertyId: string | null, dealname: string | null) => void,
  showDocuments: boolean = false,
  docStatusMap: DocStatusMap = {},
  onOpenDetail?: (deal: ClassifiedDeal) => void,
  removalStatusByDeal: RemovalStatusByDeal = {},
): ColumnDef<ClassifiedDeal>[] {
  const columns: ColumnDef<ClassifiedDeal>[] = [
    // ── Address ──────────────────────────────────────────────────────────
    {
      accessorKey: "dealname",
      id: "dealname",
      header: ({ column }) => <SortableHeader label="Address" column={column as any} />,
      cell: ({ row }) => {
        const removalState = row.original.dealId ? removalStatusByDeal[row.original.dealId] : undefined;
        const hasPending = removalState === "pending_removal" || removalState === "pending_re_addition";
        return (
          <div className="max-w-[220px] flex items-center gap-1.5">
            {hasPending && (
              <span className="shrink-0 w-2 h-2 rounded-full bg-amber-400" title="Outstanding removal request" />
            )}
            {onOpenDetail ? (
              <button
                onClick={() => onOpenDetail(row.original)}
                className="text-sm font-medium text-brandblue hover:text-brandmidblue hover:underline underline-offset-2 leading-tight text-left truncate transition-colors"
              >
                {row.original.dealname ?? "—"}
              </button>
            ) : (
              <p className="text-sm font-medium text-gray-900 leading-tight truncate">
                {row.original.dealname ?? "—"}
              </p>
            )}
          </div>
        );
      },
      enableHiding: false,
    },

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

    // ── UPRN ─────────────────────────────────────────────────────────────
    {
      accessorKey: "uprn",
      id: "uprn",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">UPRN</span>
      ),
      cell: ({ row }) => (
        <span className="text-xs font-mono text-gray-400">
          {row.original.uprn ?? "—"}
        </span>
      ),
    },

    // ── Stage badge ──────────────────────────────────────────────────────
    {
      accessorKey: "displayStage",
      id: "displayStage",
      header: ({ column }) => <SortableHeader label="Stage" column={column as any} />,
      cell: ({ row }) => <StageBadge stage={row.original.displayStage} />,
      filterFn: (row, _id, filterValue: string) =>
        row.original.displayStage === filterValue,
      enableHiding: false,
    },

    // ── Project code ─────────────────────────────────────────────────────
    {
      accessorKey: "projectCode",
      id: "projectCode",
      header: ({ column }) => <SortableHeader label="Project" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs font-medium text-gray-600 bg-gray-100 px-2 py-0.5 rounded">
          {row.original.projectCode ?? "—"}
        </span>
      ),
    },

    // ── Coordinator ──────────────────────────────────────────────────────
    {
      accessorKey: "coordinator",
      id: "coordinator",
      header: ({ column }) => <SortableHeader label="Coordinator" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-sm text-gray-700">
          {row.original.coordinator ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Designer ─────────────────────────────────────────────────────────
    {
      accessorKey: "designer",
      id: "designer",
      header: ({ column }) => <SortableHeader label="Designer" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-sm text-gray-700">
          {row.original.designer ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Installer ────────────────────────────────────────────────────────
    {
      accessorKey: "installer",
      id: "installer",
      header: ({ column }) => <SortableHeader label="Installer" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-sm text-gray-700">
          {row.original.installer ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Proposed measures ────────────────────────────────────────────────
    {
      accessorKey: "proposedMeasures",
      id: "proposedMeasures",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">
          Proposed Measures
        </span>
      ),
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2 leading-snug">
          {row.original.proposedMeasures ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Approved package ─────────────────────────────────────────────────
    {
      accessorKey: "approvedPackage",
      id: "approvedPackage",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">
          Approved Package
        </span>
      ),
      cell: ({ row }) => (
        <span className="text-xs text-gray-600">
          {row.original.approvedPackage ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Installed measures ───────────────────────────────────────────────
    {
      accessorKey: "actualMeasuresInstalled",
      id: "actualMeasuresInstalled",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">
          Installed
        </span>
      ),
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2">
          {row.original.actualMeasuresInstalled ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Pre-SAP score ────────────────────────────────────────────────────
    {
      accessorKey: "preSapScore",
      id: "preSapScore",
      header: ({ column }) => <SortableHeader label="Pre-SAP" column={column as any} />,
      cell: ({ row }) => {
        const score = row.original.preSapScore;
        if (!score) return <span className="text-gray-300">—</span>;
        const n = Number(score);
        const colour =
          n < 30
            ? "text-red-600 bg-red-50"
            : n < 50
              ? "text-amber-700 bg-amber-50"
              : "text-emerald-700 bg-emerald-50";
        return (
          <span className={`text-xs font-semibold px-2 py-0.5 rounded ${colour}`}>
            {score}
          </span>
        );
      },
    },


    // ── EI score ─────────────────────────────────────────────────────────
    {
      accessorKey: "eiScore",
      id: "eiScore",
      header: ({ column }) => <SortableHeader label="EI Score" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs font-mono text-gray-600">
          {row.original.eiScore ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── EI score (potential) ──────────────────────────────────────────────
    {
      accessorKey: "eiScorePotential",
      id: "eiScorePotential",
      header: ({ column }) => <SortableHeader label="EI Score (Potential)" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs font-mono text-gray-600">
          {row.original.eiScorePotential ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── EPC SAP score ─────────────────────────────────────────────────────
    {
      accessorKey: "epcSapScore",
      id: "epcSapScore",
      header: ({ column }) => <SortableHeader label="EPC SAP Score" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs font-mono text-gray-600">
          {row.original.epcSapScore ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── EPC SAP score (potential) ─────────────────────────────────────────
    {
      accessorKey: "epcSapScorePotential",
      id: "epcSapScorePotential",
      header: ({ column }) => <SortableHeader label="EPC SAP (Potential)" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs font-mono text-gray-600">
          {row.original.epcSapScorePotential ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Lodgement status ─────────────────────────────────────────────────
    {
      accessorKey: "lodgementStatus",
      id: "lodgementStatus",
      header: ({ column }) => <SortableHeader label="Lodgement" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600">
          {row.original.lodgementStatus ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Design date ──────────────────────────────────────────────────────
    {
      accessorKey: "designDate",
      id: "designDate",
      header: ({ column }) => <SortableHeader label="Design Date" column={column as any} />,
      cell: ({ row }) => {
        const d = row.original.designDate;
        return (
          <span className="text-xs text-gray-500">
            {d ? new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "2-digit" }) : <span className="text-gray-300">—</span>}
          </span>
        );
      },
    },

    // ── Full lodgement date ──────────────────────────────────────────────
    {
      accessorKey: "fullLodgementDate",
      id: "fullLodgementDate",
      header: ({ column }) => <SortableHeader label="Lodgement Date" column={column as any} />,
      cell: ({ row }) => {
        const d = row.original.fullLodgementDate;
        return (
          <span className="text-xs text-gray-500">
            {d ? new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "2-digit" }) : <span className="text-gray-300">—</span>}
          </span>
        );
      },
    },

  ];

  if (showDocuments) {
    columns.push({
      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];
        const isComplete = status?.isSurveyComplete;
        const hasDocs = status?.hasSurveyDocs;

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

        if (isComplete) {
          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 (hasDocs) {
          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,
    });
  }

  return columns;
}
