"use client";

import { CheckCircle2, Circle } from "lucide-react";
import type { ClassifiedDeal } from "../types";

export type DrawerSection = "survey" | "measures" | "pibi" | "domna" | "technical";

export const SECTION_TITLES: Record<DrawerSection, string> = {
  survey: "Survey",
  measures: "Measures",
  pibi: "PIBI",
  domna: "Domna Survey",
  technical: "Technical Approved",
};

export const WRITE_ROLES = ["creator", "admin", "write"];

export function formatDate(d: Date | string | null | undefined): string | null {
  if (!d) return null;
  try {
    return new Date(d).toLocaleDateString("en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return null;
  }
}

export function formatDateTime(d: string | Date | null | undefined): string {
  if (!d) return "";
  try {
    return new Date(d).toLocaleString("en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return "";
  }
}

export function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  if (!value) return null;
  return (
    <div className="flex items-start gap-3 py-2 border-b border-gray-50 last:border-0">
      <span className="text-xs text-gray-400 font-medium w-32 shrink-0 pt-0.5">{label}</span>
      <span className="text-xs text-gray-700 flex-1 leading-relaxed">{value}</span>
    </div>
  );
}

export function SectionHeader({ id, label }: { id: string; label: string }) {
  return (
    <h3
      data-testid={`drawer-section-${id}`}
      className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3"
    >
      {label}
    </h3>
  );
}

const MILESTONES: { label: string; field: keyof ClassifiedDeal; sublabel?: string }[] = [
  { label: "Booking Confirmed",    field: "confirmedSurveyDate" },
  { label: "Assessment Completed", field: "surveyedDate" },
  { label: "Coordination (V1)",    field: "ioeV1Date",            sublabel: "IOE/MTP V1" },
  { label: "Coordination (V2)",    field: "ioeV2Date",            sublabel: "IOE/MTP V2" },
  { label: "Design Completed",     field: "designDate" },
  { label: "Measures Lodged",      field: "measuresLodgementDate" },
  { label: "Stage 1 Lodgement",    field: "fullLodgementDate" },
];

export function MilestoneTimeline({ deal }: { deal: ClassifiedDeal }) {
  const milestones = MILESTONES.map((m) => ({
    ...m,
    date: formatDate(deal[m.field] as Date | string | null),
  }));

  const lastCompletedIdx = milestones.reduce((acc, m, i) => (m.date ? i : acc), -1);

  return (
    <div className="relative">
      {milestones.map((m, i) => {
        const completed = !!m.date;
        const isLast = i === milestones.length - 1;

        return (
          <div key={m.field} className="flex items-stretch gap-3">
            <div className="flex flex-col items-center w-5 shrink-0">
              <div className={`relative z-10 flex items-center justify-center w-5 h-5 rounded-full border-2 mt-0.5 transition-all duration-300 ${
                completed
                  ? "bg-brandmidblue border-brandmidblue"
                  : i <= lastCompletedIdx + 1
                    ? "bg-white border-brandblue/30"
                    : "bg-white border-gray-200"
              }`}>
                {completed ? (
                  <CheckCircle2 className="h-3 w-3 text-white" />
                ) : (
                  <Circle className={`h-2 w-2 ${i <= lastCompletedIdx + 1 ? "text-brandblue/40" : "text-gray-300"}`} />
                )}
              </div>
              {!isLast && (
                <div className={`w-0.5 flex-1 my-0.5 ${
                  completed && milestones[i + 1]?.date ? "bg-brandmidblue/40" : "bg-gray-100"
                }`} />
              )}
            </div>

            <div className={`pb-4 flex-1 min-w-0 ${isLast ? "pb-0" : ""}`}>
              <div className="flex items-start justify-between gap-2">
                <div>
                  <p className={`text-xs font-semibold leading-tight ${
                    completed ? "text-gray-800" : "text-gray-400"
                  }`}>
                    {m.label}
                  </p>
                  {m.sublabel && (
                    <p className="text-[10px] text-gray-400 mt-0.5">{m.sublabel}</p>
                  )}
                </div>
                {m.date ? (
                  <span className="text-[11px] font-medium text-brandmidblue bg-brandlightblue/60 px-2 py-0.5 rounded-full shrink-0 whitespace-nowrap">
                    {m.date}
                  </span>
                ) : (
                  <span className="text-[11px] text-gray-300 shrink-0">Pending</span>
                )}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}
