"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import { Home, AlertTriangle, ToggleLeft, ToggleRight } from "lucide-react";
import { Card, CardContent } from "@/app/shadcn_components/ui/card";
import SurveyedResultsPieChart from "./SurveyedResultsPieChart";
import DampMouldRiskPanel from "./DampMouldRiskPanel";
import CompletionTrendsChart from "./CompletionTrendsChart";
import SurveyIssuesPanel from "./SurveyIssuesPanel";
import { STAGE_COLORS, STAGE_ORDER } from "./types";
import type {
  ProjectData,
  ClassifiedDeal,
  TableModal,
  FunnelStage,
  DisplayStage,
} from "./types";

// -----------------------------------------------------------------------
// Stat card (reused from original LiveTracker)
// -----------------------------------------------------------------------
function StatCard({
  icon: Icon,
  title,
  value,
  subtitle,
  onClick,
  accent = "brandblue",
}: {
  icon: React.ElementType;
  title: string;
  value: string | number;
  subtitle?: string;
  onClick: () => void;
  accent?: "brandblue" | "red" | "bright-red";
}) {
  const accentConfig = {
    brandblue: {
      gradient: "from-brandlightblue/30 to-brandlightblue/10",
      border: "border-brandblue/20",
      text: "text-brandblue",
      value: "text-brandblue",
      hover: "hover:border-brandblue/40 hover:shadow-lg",
      icon: "text-brandblue",
    },
    red: {
      gradient: "from-red-100/30 to-red-50/20",
      border: "border-red-300/40",
      text: "text-red-500",
      value: "text-red-500",
      hover: "hover:border-red-300/60 hover:shadow-lg",
      icon: "text-red-500",
    },
    "bright-red": {
      gradient: "from-red-100 to-red-50",
      border: "border-red-500",
      text: "text-red-700",
      value: "text-red-900",
      hover: "hover:border-red-600 hover:shadow-lg",
      icon: "text-red-700",
    },
  };
  const config = accentConfig[accent];

  return (
    <motion.button
      onClick={onClick}
      whileHover={{ scale: 1.02 }}
      className={`group relative text-left border rounded-xl bg-gradient-to-br ${config.gradient} ${config.border} transition-all duration-300 shadow-sm ${config.hover} p-6`}
    >
      <div className="flex items-center justify-between">
        <div>
          <p
            className={`text-xs uppercase tracking-wide font-semibold ${config.text} opacity-70 mb-3`}
          >
            {title}
          </p>
          <p
            className={`text-3xl font-bold ${config.value} opacity-50 group-hover:opacity-75 transition-opacity`}
          >
            {value}
            {subtitle && (
              <span className="text-base font-medium text-gray-600 ml-2">
                {subtitle}
              </span>
            )}
          </p>
        </div>
        <Icon
          className={`h-8 w-8 ${config.icon} opacity-40 group-hover:opacity-70 transition-all duration-300`}
        />
      </div>
    </motion.button>
  );
}

// -----------------------------------------------------------------------
// Per-stage column config for the drill-down table
// -----------------------------------------------------------------------
type StageTableConfig = {
  cols: (keyof ClassifiedDeal)[];
  labels: Partial<Record<keyof ClassifiedDeal, string>>;
};

const STAGE_TABLE_CONFIG: Record<string, StageTableConfig> = {
  "Booking in Progress": {
    cols: ["dealname", "landlordPropertyId", "confirmedSurveyDate", "ioeV1Date"],
    labels: {
      dealname: "Address",
      landlordPropertyId: "Ref",
      confirmedSurveyDate: "Confirmed Survey Date",
      ioeV1Date: "Expected Commencement",
    },
  },
  "Assessment in Progress": {
    cols: ["dealname", "landlordPropertyId", "confirmedSurveyDate", "ioeV1Date", "outcome", "coordinator"],
    labels: {
      dealname: "Address",
      landlordPropertyId: "Ref",
      confirmedSurveyDate: "Confirmed Survey Date",
      ioeV1Date: "Expected Commencement",
      outcome: "Outcome",
      coordinator: "Surveyor",
    },
  },
  "Coordination in Progress": {
    cols: ["dealname", "landlordPropertyId", "coordinator", "preSapScore", "coordinationStatus"],
    labels: {
      dealname: "Address",
      landlordPropertyId: "Ref",
      coordinator: "Coordinator",
      preSapScore: "Pre-SAP Score",
      coordinationStatus: "Coordination Status",
    },
  },
  "Design in Progress": {
    cols: ["dealname", "landlordPropertyId", "designer", "proposedMeasures", "designType"],
    labels: {
      dealname: "Address",
      landlordPropertyId: "Ref",
      designer: "Designer",
      proposedMeasures: "Proposed Measures",
      designType: "Design Type",
    },
  },
  _default: {
    cols: ["dealname", "landlordPropertyId", "displayStage", "installer"],
    labels: {
      dealname: "Address",
      landlordPropertyId: "Ref",
      displayStage: "Stage",
      installer: "Installer",
    },
  },
};

// -----------------------------------------------------------------------
// Pipeline Funnel — rich card rows
// -----------------------------------------------------------------------
function PipelineFunnel({
  funnelStages,
  allDeals,
  onOpenTable,
}: {
  funnelStages: FunnelStage[];
  allDeals: ClassifiedDeal[];
  onOpenTable: (
    stage: string,
    deals: ClassifiedDeal[],
    columns?: (keyof ClassifiedDeal)[],
    columnLabels?: Partial<Record<keyof ClassifiedDeal, string>>,
    breakdown?: Record<string, ClassifiedDeal[]>,
    title?: string,
    description?: string,
    reason?: string,
  ) => void;
}) {
  const [mode, setMode] = useState<"current" | "cumulative">("current");

  const ALWAYS_VISIBLE: DisplayStage[] = ["At Lodgement", "Project Complete"];
  const visibleStages = funnelStages.filter(
    (s) => s.currentCount > 0 || s.cumulativeCount > 0 || ALWAYS_VISIBLE.includes(s.stage),
  );

  const maxCount = Math.max(
    ...visibleStages.map((s) =>
      mode === "current" ? s.currentCount : s.cumulativeCount,
    ),
    1,
  );

  return (
    <Card className="border border-brandblue/10 shadow-sm">
      <CardContent className="p-6">
        <div className="flex items-center justify-between mb-5">
          <div>
            <h3 className="text-base font-semibold text-brandblue">
              Pipeline Overview
            </h3>
            <p className="text-sm text-gray-500 mt-0.5">
              {mode === "cumulative"
                ? "Properties that have reached each stage or beyond"
                : "Properties currently at each stage"}
            </p>
          </div>
          <button
            onClick={() =>
              setMode((m) => (m === "current" ? "cumulative" : "current"))
            }
            className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg border border-brandblue/20 bg-brandblue/5 text-xs font-medium text-brandblue hover:bg-brandblue/10 transition-colors"
          >
            {mode === "cumulative" ? (
              <ToggleRight className="h-3.5 w-3.5" />
            ) : (
              <ToggleLeft className="h-3.5 w-3.5" />
            )}
            {mode === "cumulative" ? "Cumulative" : "Point-in-time"}
          </button>
        </div>

        <div className="space-y-2">
          {visibleStages.map((s) => {
            const count =
              mode === "current" ? s.currentCount : s.cumulativeCount;
            const pct = mode === "current" ? s.currentPct : s.cumulativePct;
            const pastCount = s.cumulativeCount - s.currentCount;
            const barWidth = maxCount > 0 ? (count / maxCount) * 100 : 0;
            const c = STAGE_COLORS[s.stage];

            const deals = allDeals.filter((d) =>
              mode === "current"
                ? d.displayStage === s.stage
                : STAGE_ORDER.indexOf(d.displayStage) >=
                  STAGE_ORDER.indexOf(s.stage),
            );

            return (
              <motion.button
                key={s.stage}
                whileHover={{ scale: 1.01, y: -1 }}
                transition={{ duration: 0.15 }}
                onClick={() => {
                  const { cols, labels } = STAGE_TABLE_CONFIG[s.stage] ?? STAGE_TABLE_CONFIG._default;
                  onOpenTable(`Pipeline — ${s.stage}`, deals, cols, labels);
                }}
                className={`w-full text-left rounded-xl border ${c.border} ${c.bg} p-4 shadow-sm hover:shadow-md transition-shadow`}
                type="button"
              >
                {/* Header row: dot + name + pct badge */}
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <span className={`w-2.5 h-2.5 rounded-full shrink-0 ${c.dot}`} />
                    <span className={`text-sm font-semibold ${c.text}`}>
                      {s.stage}
                    </span>
                  </div>
                  <span className={`text-xs font-medium px-2 py-0.5 rounded-full bg-white/60 ${c.text}`}>
                    {pct.toFixed(0)}%
                  </span>
                </div>

                {/* Progress bar */}
                <div className="h-2 bg-white/50 rounded-full overflow-hidden mb-3">
                  <motion.div
                    initial={{ width: 0 }}
                    animate={{ width: `${barWidth}%` }}
                    transition={{ duration: 0.7, ease: "easeOut" }}
                    className={`h-full rounded-full ${c.dot}`}
                    style={{ minWidth: count > 0 ? "0.5rem" : 0 }}
                  />
                </div>

                {/* Stats row */}
                <div className="flex items-center gap-4">
                  <div>
                    <span className={`text-2xl font-bold ${c.text}`}>{count}</span>
                    <span className={`text-xs ml-1.5 ${c.text} opacity-70`}>
                      {mode === "current" ? "here now" : "reached stage"}
                    </span>
                  </div>
                  {mode === "cumulative" && pastCount > 0 && (
                    <div className={`text-xs ${c.text} opacity-60 border-l border-current/20 pl-4`}>
                      <span className="font-semibold">{pastCount}</span>
                      {" past this stage"}
                    </div>
                  )}
                </div>
              </motion.button>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}

// -----------------------------------------------------------------------
// AnalyticsView — props
// -----------------------------------------------------------------------
interface AnalyticsViewProps {
  projects: { projectCode: string }[];
  currentProject: ProjectData;
  currentProjectCode: string;
  onProjectChange: (code: string) => void;
  onOpenTable: (
    stage: string,
    deals: ClassifiedDeal[],
    columns?: (keyof ClassifiedDeal)[],
    columnLabels?: Partial<Record<keyof ClassifiedDeal, string>>,
    breakdown?: Record<string, ClassifiedDeal[]>,
  ) => void;
  majorConditionDeals: ClassifiedDeal[];
  totalDeals: number;
}

export default function AnalyticsView({
  projects,
  currentProject,
  currentProjectCode,
  onProjectChange,
  onOpenTable,
  majorConditionDeals,
  totalDeals,
}: AnalyticsViewProps) {
  return (
    <div className="space-y-6">
      {/* Row 1: project selector + stat card (Properties in project) */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        {/* Project selector */}
        <Card className="flex flex-col justify-center items-center border border-brandblue/10 bg-gradient-to-br from-brandlightblue/20 to-white shadow-sm hover:shadow-md transition-shadow p-5">
          <div className="w-full flex flex-col">
            <p className="text-xs uppercase tracking-wide text-gray-600 mb-3 font-semibold">
              Select Project
            </p>
            <div className="relative">
              <select
                value={currentProjectCode}
                onChange={(e) => onProjectChange(e.target.value)}
                className="w-full px-4 py-2.5 pr-10 border border-brandblue/20 rounded-lg bg-white text-gray-800 font-medium text-center focus:ring-2 focus:ring-brandblue focus:border-brandblue focus:outline-none transition-all appearance-none"
              >
                {projects.map((p) =>
                  p.projectCode === "__ALL__" ? (
                    <option key="__ALL__" value="__ALL__" style={{ fontWeight: 700 }}>
                      ★ All Projects
                    </option>
                  ) : (
                    <option key={p.projectCode} value={p.projectCode}>
                      {p.projectCode}
                    </option>
                  )
                )}
              </select>
            </div>
          </div>
        </Card>

        {/* Properties in project */}
        <StatCard
          icon={Home}
          title="Properties in Project"
          value={currentProject.allDeals.length}
          onClick={() =>
            onOpenTable(
              currentProjectCode === "__ALL__" ? "All Properties" : `${currentProjectCode} — All Properties`,
              currentProject.allDeals,
              ["dealname", "landlordPropertyId"],
              { dealname: "Address Ref.", landlordPropertyId: "Property Ref." },
            )
          }
          accent="brandblue"
        />
      </div>

      {/* Row 1.5: Completion trends chart */}
      <CompletionTrendsChart
        deals={currentProject.allDeals}
        onOpenTable={onOpenTable}
      />

      {/* Row 2: section header */}
      <div className="pb-3 border-b border-brandblue/10 text-center">
        <h2 className="text-base font-bold text-brandblue">
          Project Insights —{" "}
          <span className="text-brandmidblue">
            {currentProjectCode === "__ALL__" ? "All Projects" : currentProjectCode}
          </span>
        </h2>
      </div>

      {/* Row 4: Pipeline Funnel */}
      <PipelineFunnel
        funnelStages={currentProject.progress.funnelStages}
        allDeals={currentProject.allDeals}
        onOpenTable={onOpenTable}
      />

      {/* Row 5: Damp & Mould Risk (moved up) */}
      <DampMouldRiskPanel
        risk={currentProject.progress.dampMouldRisk}
        onOpenTable={onOpenTable}
      />

      {/* Row 6: Survey Issues */}
      <SurveyIssuesPanel
        deals={currentProject.allDeals}
        onOpenTable={onOpenTable}
      />
    </div>
  );
}
