"use client";

import React, { useState } from "react";
import { Card, CardContent } from "@/app/shadcn_components/ui/card";
import { Button } from "@/app/shadcn_components/ui/button";
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from "@/app/shadcn_components/ui/drawer";
import { Badge } from "@/app/shadcn_components/ui/badge";

// Types
interface PropertySummary {
  id: bigint;
  uprn: bigint;
  address: string;
  postcode: string;
  decent_homes: "pass" | "fail" | "no_data";
  criterion_a: "pass" | "fail" | "no_data";
  criterion_b: "pass" | "fail" | "no_data";
  criterion_c: "pass" | "fail" | "no_data";
  criterion_d: "pass" | "fail" | "no_data";
  replacements?: { sub_variable: string; expiry_date: string | null }[];
}

interface Props {
  data: PropertySummary[];
  portfolioId: string;
}

// --- Urgency Badge for notifications ---
function UrgencyBadge({ label }: { label: string }) {
  const colorMap: Record<string, string> = {
    Overdue: "bg-red-600",
    "0–6 months": "bg-orange-500",
    "6–12 months": "bg-yellow-500",
    ">12 months": "bg-green-600",
  };
  return (
    <Badge className={`${colorMap[label]} text-white text-xs px-2 py-1`}>
      {label}
    </Badge>
  );
}

function NotificationsPanel({
  data,
  portfolioId,
}: {
  data: PropertySummary[];
  portfolioId: string;
}) {
  const today = new Date();
  const groups: Record<
    string,
    {
      property: PropertySummary;
      sub_variable: string;
      expiry: Date;
      remaining: string;
    }[]
  > = {
    Overdue: [],
    "0–6 months": [],
    "6–12 months": [],
    ">12 months": [],
  };

  data.forEach((p) => {
    p.replacements?.forEach((r) => {
      if (!r.expiry_date) return;
      const expiry = new Date(r.expiry_date);
      const diffMs = expiry.getTime() - today.getTime();
      const diffMonths = diffMs / (1000 * 60 * 60 * 24 * 30);

      const years = Math.floor(Math.abs(diffMonths) / 12);
      const months = Math.floor(Math.abs(diffMonths) % 12);

      let remaining = "";
      if (diffMs < 0) {
        remaining = `Expired ${years > 0 ? `${years}y ` : ""}${months}m ago`;
      } else {
        remaining = `${years > 0 ? `${years}y ` : ""}${months}m remaining`;
      }

      if (diffMs < 0) {
        groups.Overdue.push({
          property: p,
          sub_variable: r.sub_variable,
          expiry,
          remaining,
        });
      } else if (diffMonths <= 6) {
        groups["0–6 months"].push({
          property: p,
          sub_variable: r.sub_variable,
          expiry,
          remaining,
        });
      } else if (diffMonths <= 12) {
        groups["6–12 months"].push({
          property: p,
          sub_variable: r.sub_variable,
          expiry,
          remaining,
        });
      } else {
        groups[">12 months"].push({
          property: p,
          sub_variable: r.sub_variable,
          expiry,
          remaining,
        });
      }
    });
  });

  const groupOrder: (keyof typeof groups)[] = [
    "Overdue",
    "0–6 months",
    "6–12 months",
    ">12 months",
  ];

  return (
    <div className="mt-10">
      <h2 className="text-lg font-semibold mb-4 text-brandbrown">
        Upcoming Replacements
      </h2>
      <Card className="max-h-[600px] overflow-y-auto">
        <CardContent className="p-4 space-y-2">
          {groupOrder.map((urgency) =>
            groups[urgency].length > 0 ? (
              <div key={urgency}>
                <div className="flex items-center space-x-2 mb-3">
                  <UrgencyBadge label={urgency} />
                  <span className="text-gray-700 font-medium">
                    {groups[urgency].length} item
                    {groups[urgency].length > 1 ? "s" : ""}
                  </span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-1">
                  {groups[urgency].map((item, idx) => (
                    <div
                      key={idx}
                      className="p-4 bg-gray-50 rounded-md border hover:bg-gray-100 transition cursor-pointer flex flex-col justify-between"
                      onClick={() =>
                        window.open(
                          `/portfolio/${portfolioId}/building-passport/${item.property.id}/decent-homes`,
                          "_blank"
                        )
                      }
                    >
                      <div>
                        <div className="font-medium text-gray-800">
                          {item.sub_variable}
                        </div>
                        <div className="text-sm text-gray-500">
                          {item.property.address}
                        </div>
                      </div>
                      <div className="mt-2 flex justify-between text-sm text-gray-600">
                        <span>{item.remaining}</span>
                        <span>
                          Expiry Date: {item.expiry.toLocaleDateString("en-GB")}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : null
          )}
        </CardContent>
      </Card>
    </div>
  );
}

// --- Dashboard ---
const DecentHomesDashboard: React.FC<Props> = ({ data, portfolioId }) => {
  const [open, setOpen] = useState(false);
  const [selectedGroup, setSelectedGroup] = useState<PropertySummary[]>([]);
  const [selectedTitle, setSelectedTitle] = useState("");

  const total = data.length;
  const passes = data.filter((p) => p.decent_homes === "pass");
  const noData = data.filter((p) => p.decent_homes === "no_data");
  const critAFails = data.filter((p) => p.criterion_a === "fail");
  const critBFails = data.filter((p) => p.criterion_b === "fail");
  const critCFails = data.filter((p) => p.criterion_c === "fail");
  const critDFails = data.filter((p) => p.criterion_d === "fail");

  // print the no datas

  const overallPassRate = ((passes.length / total) * 100).toFixed(1);

  const openDrawer = (group: PropertySummary[], title: string) => {
    setSelectedGroup(group);
    setSelectedTitle(title);
    setOpen(true);
  };

  return (
    <div className="container mx-auto px-4 py-6">
      <h1 className="text-2xl font-semibold mb-6">
        Decent Homes Portfolio Summary
      </h1>

      {/* 8 compact cards in a 2x4 grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {/* Overall Pass Rate */}
        <div className="rounded-xl bg-brandblue p-[3px]">
          <div className="rounded-lg bg-brandbrown p-[3px]">
            <div className="rounded-md bg-brandblue h-full">
              <CardContent className="p-4 text-center flex flex-col items-center justify-center space-y-2 h-full">
                <div className="text-sm uppercase tracking-wider font-semibold text-brandbrown">
                  Overall Pass Rate
                </div>
                <div className="text-3xl font-extrabold text-white drop-shadow">
                  {overallPassRate}%
                </div>
                <div className="text-sm font-medium text-white/80">
                  <span className="text-brandbrown font-semibold">
                    {passes.length}
                  </span>{" "}
                  out of{" "}
                  <span className="text-brandbrown font-semibold">{total}</span>{" "}
                  properties
                </div>
              </CardContent>
            </div>
          </div>
        </div>

        {/* Criterion A */}
        <Card
          onClick={() => openDrawer(critAFails, "Criterion A Fails")}
          className="cursor-pointer transition hover:bg-hoverblue hover:text-white"
        >
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">
              Criterion A Fails
            </div>
            <div className="text-3xl font-bold text-brandbrown">
              {critAFails.length}
            </div>
            <div className="text-sm text-brandbrown/80">
              properties affected
            </div>
          </CardContent>
        </Card>

        {/* Criterion B */}
        <Card
          onClick={() => openDrawer(critBFails, "Criterion B Fails")}
          className="cursor-pointer transition hover:bg-hoverblue hover:text-white"
        >
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">
              Criterion B Fails
            </div>
            <div className="text-3xl font-bold text-brandbrown">
              {critBFails.length}
            </div>
            <div className="text-sm text-brandbrown/80">
              properties affected
            </div>
          </CardContent>
        </Card>

        {/* Criterion C */}
        <Card
          onClick={() => openDrawer(critCFails, "Criterion C Fails")}
          className="cursor-pointer transition hover:bg-hoverblue hover:text-white"
        >
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">
              Criterion C Fails
            </div>
            <div className="text-3xl font-bold text-brandbrown">
              {critCFails.length}
            </div>
            <div className="text-sm text-brandbrown/80">
              properties affected
            </div>
          </CardContent>
        </Card>

        {/* Criterion D */}
        <Card
          onClick={() => openDrawer(critDFails, "Criterion D Fails")}
          className="cursor-pointer transition hover:bg-hoverblue hover:text-white"
        >
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">
              Criterion D Fails
            </div>
            <div className="text-3xl font-bold text-brandbrown">
              {critDFails.length}
            </div>
            <div className="text-sm text-brandbrown/80">
              properties affected
            </div>
          </CardContent>
        </Card>

        {/* Survey information missing */}
        <Card
          onClick={() => openDrawer(noData, "Survey information missing")}
          className="cursor-pointer transition hover:bg-hoverblue hover:text-white"
        >
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">
              Survey information missing
            </div>
            <div className="text-3xl font-bold text-brandbrown">
              {noData.length}
            </div>
            <div className="text-sm text-brandbrown/80">
              properties affected
            </div>
          </CardContent>
        </Card>

        {/* Passes */}
        <Card
          onClick={() => openDrawer(passes, "Passes Decent Homes")}
          className="cursor-pointer transition hover:bg-hoverblue hover:text-white"
        >
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">Passes</div>
            <div className="text-3xl font-bold text-brandbrown">
              {passes.length}
            </div>
            <div className="text-sm text-brandbrown/80">properties</div>
          </CardContent>
        </Card>

        {/* Total Properties */}
        <Card className="transition">
          <CardContent className="p-4 text-center">
            <div className="text-brandbrown font-semibold">
              Total Properties
            </div>
            <div className="text-3xl font-bold text-brandbrown">{total}</div>
            <div className="text-sm text-brandbrown/80">portfolio size</div>
          </CardContent>
        </Card>
      </div>

      {/* Notifications */}
      <NotificationsPanel data={data} portfolioId={portfolioId} />

      {/* Drawer */}
      <Drawer open={open} onOpenChange={setOpen}>
        <DrawerContent className="p-4 w-full max-w-md ml-auto border-l h-full overflow-y-auto">
          <DrawerHeader>
            <DrawerTitle>{selectedTitle}</DrawerTitle>
          </DrawerHeader>
          <ul className="space-y-4">
            {selectedGroup.map((p) => (
              <li key={String(p.id)} className="border rounded p-4">
                <div className="font-semibold">
                  {p.address} ({p.postcode})
                </div>
                <div className="text-sm text-muted-foreground mb-2">
                  UPRN: {String(p.uprn)}
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  className="mt-3 bg-brandblue text-white hover:bg-hoverblue hover:text-gray-100"
                  onClick={() =>
                    // If all options are no_data, we open the /assessment page, otherwise we open the /decent-homes page
                    p.decent_homes === "no_data" &&
                    p.criterion_a === "no_data" &&
                    p.criterion_b === "no_data" &&
                    p.criterion_c === "no_data" &&
                    p.criterion_d === "no_data"
                      ? window.open(
                          `/portfolio/${portfolioId}/building-passport/${p.id}`,
                          "_blank"
                        )
                      : window.open(
                          `/portfolio/${portfolioId}/building-passport/${p.id}/decent-homes`,
                          "_blank"
                        )
                  }
                >
                  View Property
                </Button>
              </li>
            ))}
          </ul>
        </DrawerContent>
      </Drawer>
    </div>
  );
};

export default DecentHomesDashboard;
