"use client";

import { motion } from "framer-motion";
import { Droplets, AlertTriangle, ShieldAlert } from "lucide-react";
import { Card, CardContent } from "@/app/shadcn_components/ui/card";
import type { DampMouldRiskData, ClassifiedDeal } from "./types";

interface DampMouldRiskPanelProps {
  risk: DampMouldRiskData;
  onOpenTable: (
    stage: string,
    deals: ClassifiedDeal[],
    columns?: (keyof ClassifiedDeal)[],
    columnLabels?: Partial<Record<keyof ClassifiedDeal, string>>
  ) => void;
}

function RiskStatCard({
  label,
  subtitle,
  count,
  total,
  icon: Icon,
  color,
  onClick,
}: {
  label: string;
  subtitle: string;
  count: number;
  total: number;
  icon: React.ElementType;
  color: "amber" | "orange" | "red";
  onClick: () => void;
}) {
  const pct = total > 0 ? ((count / total) * 100).toFixed(1) : "0.0";

  const styles = {
    amber: {
      gradient: "from-amber-50 to-amber-50/30",
      border: "border-amber-200",
      hover: "hover:border-amber-300 hover:shadow-md",
      icon: "text-amber-500",
      badge: "bg-amber-100 text-amber-700",
      bar: "bg-amber-400",
      value: "text-amber-700",
    },
    orange: {
      gradient: "from-orange-50 to-orange-50/30",
      border: "border-orange-200",
      hover: "hover:border-orange-300 hover:shadow-md",
      icon: "text-orange-500",
      badge: "bg-orange-100 text-orange-700",
      bar: "bg-orange-400",
      value: "text-orange-700",
    },
    red: {
      gradient: "from-red-50 to-red-50/30",
      border: "border-red-300",
      hover: "hover:border-red-400 hover:shadow-md",
      icon: "text-red-500",
      badge: "bg-red-100 text-red-700",
      bar: "bg-red-500",
      value: "text-red-700",
    },
  };

  const s = styles[color];

  return (
    <motion.button
      whileHover={{ scale: 1.02 }}
      onClick={onClick}
      disabled={count === 0}
      className={`group w-full text-left rounded-xl border bg-gradient-to-br ${s.gradient} ${s.border} ${s.hover} p-5 transition-all duration-200 shadow-sm disabled:opacity-50 disabled:cursor-default`}
    >
      <div className="flex items-start justify-between mb-3">
        <div className="p-2 rounded-lg bg-white/70">
          <Icon className={`h-4 w-4 ${s.icon}`} />
        </div>
        <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${s.badge}`}>
          {pct}%
        </span>
      </div>

      <p className={`text-2xl font-bold ${s.value} mb-0.5`}>{count}</p>
      <p className="text-sm font-medium text-gray-700">{label}</p>
      <p className="text-xs text-gray-500 mt-0.5">{subtitle}</p>

      {/* Mini progress bar */}
      <div className="mt-3 h-1 bg-gray-200 rounded-full overflow-hidden">
        <div
          className={`h-full ${s.bar} rounded-full transition-all duration-700`}
          style={{ width: `${Math.min(Number(pct), 100)}%` }}
        />
      </div>
    </motion.button>
  );
}

export default function DampMouldRiskPanel({
  risk,
  onOpenTable,
}: DampMouldRiskPanelProps) {
  const { totalDeals } = risk;

  const surveyColumns: (keyof ClassifiedDeal)[] = [
    "dealname",
    "landlordPropertyId",
    "dampMouldFlag",
    "majorConditionIssueDescription",
    "majorConditionIssuePhotosS3",
  ];

  const surveyLabels: Partial<Record<keyof ClassifiedDeal, string>> = {
    dealname: "Address",
    landlordPropertyId: "Property Ref",
    dampMouldFlag: "Damp & Mould",
    majorConditionIssueDescription: "Surveyor Notes",
    majorConditionIssuePhotosS3: "Photo Evidence",
  };

  const coordColumns: (keyof ClassifiedDeal)[] = [
    "dealname",
    "landlordPropertyId",
    "dampMouldFlag",
    "dampMouldAndRepairComments",
    "coordinator",
  ];

  const coordLabels: Partial<Record<keyof ClassifiedDeal, string>> = {
    dealname: "Address",
    landlordPropertyId: "Property Ref",
    dampMouldFlag: "Damp & Mould",
    dampMouldAndRepairComments: "Comments",
    coordinator: "Coordinator",
  };

  const noRisk =
    risk.surveyFlagCount === 0 &&
    risk.coordinatorFlagCount === 0;

  return (
    <Card className="border border-amber-200/60 bg-gradient-to-br from-amber-50/40 to-white shadow-sm">
      <CardContent className="p-6">
        {/* Header */}
        <div className="flex items-start gap-3 mb-5">
          <div className="p-2.5 rounded-xl bg-amber-100 border border-amber-200">
            <Droplets className="h-5 w-5 text-amber-600" />
          </div>
          <div>
            <h3 className="text-base font-semibold text-gray-800">
              Awaab&apos;s Law — Damp, Mould & Other Condition Issues
            </h3>
            <p className="text-sm text-gray-500 mt-0.5">
              Comparison of flags raised at survey vs coordination stage
            </p>
          </div>
        </div>

        {noRisk ? (
          <div className="flex items-center gap-3 py-4 px-4 rounded-xl bg-emerald-50 border border-emerald-200">
            <div className="p-1.5 rounded-lg bg-emerald-100">
              <ShieldAlert className="h-4 w-4 text-emerald-600" />
            </div>
            <p className="text-sm font-medium text-emerald-700">
              No condition issues recorded for this project.
            </p>
          </div>
        ) : (
          <>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-4">
              <RiskStatCard
                label="Flagged at Survey"
                subtitle="Identified by assessor"
                count={risk.surveyFlagCount}
                total={totalDeals}
                icon={AlertTriangle}
                color="red"
                onClick={() =>
                  onOpenTable(
                    "Condition Issues — Survey Stage",
                    risk.surveyFlagDeals,
                    surveyColumns,
                    surveyLabels
                  )
                }
              />
              <RiskStatCard
                label="Flagged at Coordination"
                subtitle="Identified after survey"
                count={risk.coordinatorFlagCount}
                total={totalDeals}
                icon={Droplets}
                color="red"
                onClick={() =>
                  onOpenTable(
                    "Condition Issues — Coordination Stage",
                    risk.coordinatorFlagDeals,
                    coordColumns,
                    coordLabels
                  )
                }
              />
            </div>

            {/* Missed risk callout */}
            {risk.coordinatorFlagCount > risk.surveyFlagCount && (
              <div className="flex items-start gap-2.5 p-3.5 rounded-lg bg-orange-50 border border-orange-200">
                <AlertTriangle className="h-4 w-4 text-orange-500 mt-0.5 shrink-0" />
                <p className="text-xs text-orange-700 leading-relaxed">
                  <span className="font-semibold">
                    {risk.coordinatorFlagCount - risk.surveyFlagCount} additional{" "}
                    {risk.coordinatorFlagCount - risk.surveyFlagCount === 1 ? "property was" : "properties were"}{" "}
                  </span>
                  flagged with condition issues at the coordination stage that{" "}
                  {risk.coordinatorFlagCount - risk.surveyFlagCount === 1 ? "was" : "were"} not
                  identified during the initial survey.
                </p>
              </div>
            )}
          </>
        )}
      </CardContent>
    </Card>
  );
}
