"use client";

import { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown, CheckCircle2, AlertCircle, FileX } from "lucide-react";
import Link from "next/link";
import type { ClassifiedDeal, DocStatusMap, RemovalStatusByDeal } from "./types";
import { StageBadge } from "./ui";

// 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, batch: string | null, batchDescription: string | null) => void,
  showDocuments: boolean = false,
  docStatusMap: DocStatusMap = {},
  portfolioId: string = "",
  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";
        const href = portfolioId
          ? `/portfolio/${portfolioId}/your-projects/live/${row.original.dealId}`
          : undefined;
        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" />
            )}
            {href ? (
              <Link
                href={href}
                data-testid="property-row-link"
                className="text-sm font-medium text-brandblue hover:text-brandmidblue hover:underline underline-offset-2 leading-tight truncate transition-colors"
              >
                {row.original.dealname ?? "—"}
              </Link>
            ) : (
              <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: "potentialPostSapScoreDropdown",
      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.potentialPostSapScoreDropdown ?? <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>
      ),
    },

    // ── Surveyed date ────────────────────────────────────────────────────
    {
      accessorKey: "surveyedDate",
      id: "surveyedDate",
      header: ({ column }) => <SortableHeader label="Surveyed Date" column={column as any} />,
      cell: ({ row }) => {
        const d = row.original.surveyedDate;
        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>
        );
      },
    },

    // ── 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>
        );
      },
    },

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

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

    // ── Group description ────────────────────────────────────────────────
    {
      accessorKey: "batchDescription",
      id: "batchDescription",
      header: ({ column }) => <SortableHeader label="Group Description" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[220px] line-clamp-2 leading-snug">
          {row.original.batchDescription ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

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

    // ── Damp and mould growth ────────────────────────────────────────────
    {
      id: "dampAndMouldGrowth",
      accessorFn: (row) => row.dampMouldFlag,
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">
          Damp &amp; Mould Growth
        </span>
      ),
      cell: ({ row }) => (
        <span className="text-xs text-gray-600">
          {row.original.dampMouldFlag ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Damp, mould and repair comments ─────────────────────────────────
    {
      accessorKey: "dampMouldAndRepairComments",
      id: "dampMouldAndRepairComments",
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">
          Damp, Mould &amp; Repair Comments
        </span>
      ),
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[220px] line-clamp-2 leading-snug">
          {row.original.dampMouldAndRepairComments ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Domna survey required ────────────────────────────────────────────
    {
      id: "domnaSurveyRequested",
      accessorFn: (row) => row.domnasurveyRequired,
      header: () => (
        <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">
          Domna Survey Required
        </span>
      ),
      cell: ({ row }) => {
        const val = row.original.domnasurveyRequired;
        if (val === null || val === undefined) return <span className="text-gray-300">—</span>;
        return (
          <span className={`text-xs font-medium ${val ? "text-amber-700" : "text-gray-500"}`}>
            {val ? "Yes" : "No"}
          </span>
        );
      },
    },

    // ── Planning authority ───────────────────────────────────────────────
    {
      accessorKey: "planningAuthority",
      id: "planningAuthority",
      header: ({ column }) => <SortableHeader label="Planning Authority" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2 leading-snug">
          {row.original.planningAuthority ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Designated area ──────────────────────────────────────────────────
    {
      accessorKey: "designatedArea",
      id: "designatedArea",
      header: ({ column }) => <SortableHeader label="Designated Area" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2 leading-snug">
          {row.original.designatedArea ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Article 4 PD rights ──────────────────────────────────────────────
    {
      accessorKey: "article4PdRights",
      id: "article4PdRights",
      header: ({ column }) => <SortableHeader label="Article 4 PD Rights" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2 leading-snug">
          {row.original.article4PdRights ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Listed building ──────────────────────────────────────────────────
    {
      accessorKey: "listedBuilding",
      id: "listedBuilding",
      header: ({ column }) => <SortableHeader label="Listed Building" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2 leading-snug">
          {row.original.listedBuilding ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Design constraints ───────────────────────────────────────────────
    {
      accessorKey: "designConstraints",
      id: "designConstraints",
      header: ({ column }) => <SortableHeader label="Design Constraints" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[220px] line-clamp-2 leading-snug">
          {row.original.designConstraints ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Planning comments ────────────────────────────────────────────────
    {
      accessorKey: "planningComments",
      id: "planningComments",
      header: ({ column }) => <SortableHeader label="Planning Comments" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[220px] line-clamp-2 leading-snug">
          {row.original.planningComments ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Planning status ──────────────────────────────────────────────────
    {
      accessorKey: "planningStatus",
      id: "planningStatus",
      header: ({ column }) => <SortableHeader label="Planning Status" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[180px] line-clamp-2 leading-snug">
          {row.original.planningStatus ?? <span className="text-gray-300">—</span>}
        </span>
      ),
    },

    // ── Planning suggested approach ──────────────────────────────────────
    {
      accessorKey: "planningSuggestedApproach",
      id: "planningSuggestedApproach",
      header: ({ column }) => <SortableHeader label="Planning Suggested Approach" column={column as any} />,
      cell: ({ row }) => (
        <span className="text-xs text-gray-600 max-w-[220px] line-clamp-2 leading-snug">
          {row.original.planningSuggestedApproach ?? <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,
                row.original.batch,
                row.original.batchDescription,
              )
            }
            className={className}
          >
            {icon}
            Docs
          </button>
        );
      },
      enableSorting: false,
      enableHiding: false,
    });
  }

  return columns;
}
