"use client";

import { motion } from "framer-motion";
import { CheckCircle2, ArrowRight } from "lucide-react";
import { Card, CardContent } from "@/app/shadcn_components/ui/card";
import { STAGE_COLORS } from "./types";
import type {
  ProjectProgressData,
  ClassifiedDeal,
} from "./types";

const EARLY_COLUMNS: (keyof ClassifiedDeal)[] = [
  "dealname",
  "landlordPropertyId",
  "displayStage",
  "preSapScore",
  "outcome",
];
const EARLY_LABELS: Partial<Record<keyof ClassifiedDeal, string>> = {
  dealname: "Address",
  landlordPropertyId: "Ref",
  displayStage: "Current Stage",
  preSapScore: "Pre-SAP Score",
  outcome: "Survey Outcome",
};

// -----------------------------------------------------------------------
// Circular progress ring (SVG)
// -----------------------------------------------------------------------
function RingProgress({
  pct,
  color = "#14163d",
  size = 80,
}: {
  pct: number;
  color?: string;
  size?: number;
}) {
  const r = 34;
  const circ = 2 * Math.PI * r;
  const offset = circ - (Math.min(pct, 100) / 100) * circ;
  return (
    <svg width={size} height={size} viewBox="0 0 80 80" className="-rotate-90">
      <circle
        cx="40"
        cy="40"
        r={r}
        fill="none"
        stroke="#e5e7eb"
        strokeWidth="6"
      />
      <circle
        cx="40"
        cy="40"
        r={r}
        fill="none"
        stroke={color}
        strokeWidth="6"
        strokeDasharray={circ}
        strokeDashoffset={offset}
        strokeLinecap="round"
        style={{ transition: "stroke-dashoffset 0.8s ease" }}
      />
    </svg>
  );
}

// -----------------------------------------------------------------------
// Main component
// -----------------------------------------------------------------------
interface ProgressOverviewProps {
  data: ProjectProgressData;
  onOpenTable?: (
    stage: string,
    deals: ClassifiedDeal[],
    columns?: (keyof ClassifiedDeal)[],
    columnLabels?: Partial<Record<keyof ClassifiedDeal, string>>,
    breakdown?: Record<string, ClassifiedDeal[]>,
  ) => void;
}

export default function ProgressOverview({
  data,
  onOpenTable,
}: ProgressOverviewProps) {
  const {
    completedPercentage,
    completedCount,
    nonQueryTotal,
    stageProgress,
  } = data;

  // Early-stage rows (scope / booking / assessment)
  const earlyStages = [
    "Scope & Planning",
    "Booking in Progress",
    "Assessment in Progress",
  ];
  const earlyItems = stageProgress.filter(
    (s) => earlyStages.includes(s.stage) && s.count > 0,
  );

  return (
    <Card className="border border-brandblue/10 shadow-md rounded-2xl bg-white">
      <CardContent className="p-6 space-y-5">
        {/* ── Completion header ──────────────────────────────────────────── */}
        <motion.button
          whileHover={{ scale: 1.01 }}
          onClick={() =>
            onOpenTable?.(
              "Completed Properties",
              data.completedDeals,
              [
                "dealname",
                "landlordPropertyId",
                "displayStage",
                "actualMeasuresInstalled",
                "fullLodgementDate",
              ],
              {
                dealname: "Address",
                landlordPropertyId: "Ref",
                displayStage: "Stage",
                actualMeasuresInstalled: "Measures Installed",
                fullLodgementDate: "Lodgement Date",
              },
            )
          }
          className="group w-full text-left rounded-xl border border-emerald-200 bg-gradient-to-r from-emerald-50 to-white p-5 hover:border-emerald-300 hover:shadow-md transition-all duration-200"
        >
          <div className="flex items-center gap-4">
            <div className="relative shrink-0">
              <RingProgress
                pct={completedPercentage}
                color="#059669"
                size={72}
              />
              <div className="absolute inset-0 flex items-center justify-center">
                <span className="text-sm font-bold text-emerald-700">
                  {completedPercentage.toFixed(0)}%
                </span>
              </div>
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                <span className="text-sm font-semibold text-emerald-800">
                  Work Completed
                </span>
              </div>
              <p className="text-2xl font-bold text-emerald-700">
                {completedCount}
                <span className="text-sm font-medium text-emerald-600/70 ml-1">
                  / {nonQueryTotal}
                </span>
              </p>
              <p className="text-xs text-emerald-600/80 mt-0.5">
                Properties fully lodged and funded
              </p>
            </div>
            <ArrowRight className="h-4 w-4 text-emerald-400 group-hover:text-emerald-600 group-hover:translate-x-0.5 transition-all shrink-0" />
          </div>
        </motion.button>

        {/* ── Early stage chips ─────────────────────────────────────────── */}
        {earlyItems.length > 0 && (
          <div className="grid grid-cols-3 gap-2">
            {earlyItems.map((item) => {
              const c = STAGE_COLORS[item.stage];
              return (
                <motion.button
                  key={item.stage}
                  whileHover={{ scale: 1.03 }}
                  onClick={() =>
                    onOpenTable?.(
                      item.stage,
                      item.deals,
                      EARLY_COLUMNS,
                      EARLY_LABELS,
                    )
                  }
                  className={`group text-left rounded-xl border p-3 transition-all duration-200 hover:shadow-md ${c.bg} ${c.border} hover:opacity-95`}
                >
                  <div className={`flex items-center gap-1 mb-1.5`}>
                    <span
                      className={`w-1.5 h-1.5 rounded-full shrink-0 ${c.dot}`}
                    />
                    <span
                      className={`text-xs font-semibold ${c.text} truncate leading-tight`}
                    >
                      {item.stage}
                    </span>
                  </div>
                  <p className={`text-xl font-bold ${c.text}`}>{item.count}</p>
                  <p className={`text-xs ${c.text} opacity-70 mt-0.5`}>
                    {item.percentage.toFixed(0)}% of total
                  </p>
                </motion.button>
              );
            })}
          </div>
        )}

      </CardContent>
    </Card>
  );
}
