"use client";

import { useMemo } from "react";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/app/shadcn_components/ui/table";
import { Separator } from "@/app/shadcn_components/ui/separator";

interface SolarPanelConfig {
  panelsCount: number;
  yearlyEnergyDcKwh: number;
}

interface SolarConfigTableProps {
  solarPanelConfigs: SolarPanelConfig[];
  panelCapacityWatts: number;
  panelLifetimeYears: number;
  panelWidthMeters: number;
  panelHeightMeters: number;
}

function ChartTooltip({
  payload,
  active,
  label,
}: {
  payload?: { name: string; value: number; color: string }[];
  active?: boolean;
  label?: string | number;
}) {
  if (!active || !payload?.length) return null;
  return (
    <div className="bg-white border border-gray-200 rounded-lg shadow-lg px-3 py-2.5 text-sm min-w-[160px]">
      <p className="font-semibold text-gray-700 mb-1.5 border-b border-gray-100 pb-1.5">
        {label} panels
      </p>
      {payload.map((item, i) => (
        <div key={i} className="flex items-center justify-between gap-3 py-0.5">
          <div className="flex items-center gap-1.5">
            <span
              className="w-2.5 h-2.5 rounded-sm shrink-0"
              style={{ backgroundColor: item.color }}
            />
            <span className="text-gray-500 text-xs">{item.name}</span>
          </div>
          <span className="font-semibold text-gray-800 text-xs">
            {Math.round(item.value).toLocaleString()} kWh
          </span>
        </div>
      ))}
    </div>
  );
}

export default function SolarConfigTable({
  solarPanelConfigs,
  panelCapacityWatts,
  panelLifetimeYears,
  panelWidthMeters,
  panelHeightMeters,
}: SolarConfigTableProps) {
  const chartData = useMemo(
    () =>
      solarPanelConfigs.map((cfg) => ({
        panels: cfg.panelsCount,
        "Annual output": cfg.yearlyEnergyDcKwh,
      })),
    [solarPanelConfigs]
  );

  return (
    <div className="space-y-8">
      {/* Efficiency curve */}
      <div>
        <p className="text-sm font-semibold text-brandblue mb-0.5">
          Solar output vs. number of panels
        </p>
        <p className="text-xs text-gray-400 mb-5">
          A curve that flattens early indicates diminishing returns as panels
          are placed on less optimal roof faces.
        </p>
        <ResponsiveContainer width="100%" height={260}>
          <AreaChart data={chartData} margin={{ top: 10, right: 16, left: 0, bottom: 24 }}>
            <defs>
              <linearGradient id="solarGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#3943b7" stopOpacity={0.18} />
                <stop offset="95%" stopColor="#3943b7" stopOpacity={0.01} />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
            <XAxis
              dataKey="panels"
              tick={{ fontSize: 10, fill: "#9ca3af" }}
              axisLine={false}
              tickLine={false}
              label={{
                value: "Number of panels",
                position: "insideBottom",
                offset: -12,
                fontSize: 10,
                fill: "#9ca3af",
              }}
              height={40}
            />
            <YAxis
              width={52}
              tick={{ fontSize: 10, fill: "#9ca3af" }}
              axisLine={false}
              tickLine={false}
              tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`}
            />
            <Tooltip content={<ChartTooltip />} cursor={{ stroke: "#3943b7", strokeWidth: 1, strokeDasharray: "4 2" }} />
            <Area
              type="monotone"
              dataKey="Annual output"
              stroke="#3943b7"
              strokeWidth={2}
              fill="url(#solarGradient)"
              dot={false}
              activeDot={{ r: 4, fill: "#3943b7", strokeWidth: 0 }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>

      <Separator />

      {/* Configurations table */}
      <div>
        <p className="text-sm font-semibold text-brandblue mb-0.5">
          All modelled configurations
        </p>
        <p className="text-xs text-gray-400 mb-4">
          Every array size considered, from the smallest viable installation to the
          maximum possible for this property.
        </p>
        <div className="rounded-lg border border-gray-200 overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow className="bg-gray-50/80">
                <TableHead className="font-semibold text-gray-500 text-xs uppercase tracking-wide">Panels</TableHead>
                <TableHead className="font-semibold text-gray-500 text-xs uppercase tracking-wide text-right">Capacity</TableHead>
                <TableHead className="font-semibold text-gray-500 text-xs uppercase tracking-wide text-right">Roof area</TableHead>
                <TableHead className="font-semibold text-gray-500 text-xs uppercase tracking-wide text-right">Annual output</TableHead>
                <TableHead className="font-semibold text-gray-500 text-xs uppercase tracking-wide text-right">
                  Lifetime output
                  <span className="ml-1 font-normal text-gray-400 normal-case">
                    ({panelLifetimeYears} yr)
                  </span>
                </TableHead>
                <TableHead className="font-semibold text-gray-500 text-xs uppercase tracking-wide text-right">kWh / kWp</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {solarPanelConfigs.map((cfg, i) => {
                const capacityKwp = (cfg.panelsCount * panelCapacityWatts) / 1000;
                const areaM2 = cfg.panelsCount * panelWidthMeters * panelHeightMeters;
                const annualKwh = Math.round(cfg.yearlyEnergyDcKwh);
                const lifetimeKwh = Math.round(cfg.yearlyEnergyDcKwh * panelLifetimeYears);
                const efficiency = Math.round(annualKwh / capacityKwp);
                const isEven = i % 2 === 0;

                return (
                  <TableRow
                    key={cfg.panelsCount}
                    className={isEven ? "bg-white" : "bg-gray-50/40"}
                  >
                    <TableCell className="font-semibold text-brandblue">
                      {cfg.panelsCount}
                    </TableCell>
                    <TableCell className="text-right text-gray-600 tabular-nums">
                      {capacityKwp.toFixed(1)}
                      <span className="ml-1 text-xs text-gray-400">kWp</span>
                    </TableCell>
                    <TableCell className="text-right text-gray-600 tabular-nums">
                      {areaM2.toFixed(1)}
                      <span className="ml-1 text-xs text-gray-400">m²</span>
                    </TableCell>
                    <TableCell className="text-right text-gray-600 tabular-nums">
                      {annualKwh.toLocaleString()}
                      <span className="ml-1 text-xs text-gray-400">kWh</span>
                    </TableCell>
                    <TableCell className="text-right text-gray-600 tabular-nums">
                      {lifetimeKwh.toLocaleString()}
                      <span className="ml-1 text-xs text-gray-400">kWh</span>
                    </TableCell>
                    <TableCell className="text-right text-gray-400 tabular-nums text-xs">
                      {efficiency.toLocaleString()}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}
