"use client";

import { useMemo } from "react";

interface SolarPanel {
  center: { latitude: number; longitude: number };
  orientation: "LANDSCAPE" | "PORTRAIT";
  segmentIndex: number;
  yearlyEnergyDcKwh: number;
}

interface RoofSegmentStat {
  segmentIndex: number;
  azimuthDegrees: number;
  center: { latitude: number; longitude: number };
  stats: { groundAreaMeters2: number };
}

interface SolarPanelMapProps {
  activePanels: SolarPanel[];
  roofSegmentStats: RoofSegmentStat[];
  panelWidthMeters: number;
  panelHeightMeters: number;
  buildingCenter: { latitude: number; longitude: number };
}

const SEGMENT_STYLES = [
  { fill: "#fef9c3", stroke: "#ca8a04", text: "#92400e" },
  { fill: "#dbeafe", stroke: "#2563eb", text: "#1e40af" },
  { fill: "#dcfce7", stroke: "#16a34a", text: "#166534" },
  { fill: "#fce7f3", stroke: "#db2777", text: "#9d174d" },
];

const PANEL_COLORS = ["#ca8a04", "#2563eb", "#16a34a", "#db2777"];

const SVG_W = 560;
const SVG_H = 440;
const PAD = 56;

function getCardinal(az: number): string {
  const dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
  return dirs[Math.round((((az % 360) + 360) % 360) / 45) % 8];
}

function CompassRose({ cx, cy, r }: { cx: number; cy: number; r: number }) {
  return (
    <g>
      <circle cx={cx} cy={cy} r={r + 5} fill="white" stroke="#e5e7eb" strokeWidth={1} />
      <polygon
        points={`${cx},${cy - r} ${cx - r * 0.3},${cy + r * 0.1} ${cx + r * 0.3},${cy + r * 0.1}`}
        fill="#1e3a5f"
      />
      <polygon
        points={`${cx},${cy + r} ${cx - r * 0.3},${cy - r * 0.1} ${cx + r * 0.3},${cy - r * 0.1}`}
        fill="#d1d5db"
      />
      <line x1={cx - r} y1={cy} x2={cx + r} y2={cy} stroke="#9ca3af" strokeWidth={1} />
      <text x={cx} y={cy - r - 6} textAnchor="middle" fontSize={11} fontWeight="700" fill="#1e3a5f">N</text>
      <text x={cx} y={cy + r + 14} textAnchor="middle" fontSize={10} fill="#9ca3af">S</text>
      <text x={cx + r + 10} y={cy + 4} textAnchor="middle" fontSize={10} fill="#9ca3af">E</text>
      <text x={cx - r - 10} y={cy + 4} textAnchor="middle" fontSize={10} fill="#9ca3af">W</text>
    </g>
  );
}

export default function SolarPanelMap({
  activePanels,
  roofSegmentStats,
  panelWidthMeters,
  panelHeightMeters,
  buildingCenter,
}: SolarPanelMapProps) {
  const mPerLng = 111320 * Math.cos((buildingCenter.latitude * Math.PI) / 180);
  const mPerLat = 111320;
  const cx = SVG_W / 2;
  const cy = SVG_H / 2;

  const scale = useMemo(() => {
    const allM = [
      ...activePanels.map((p) => ({
        x: (p.center.longitude - buildingCenter.longitude) * mPerLng,
        y: (p.center.latitude - buildingCenter.latitude) * mPerLat,
      })),
      ...roofSegmentStats.map((s) => ({
        x: (s.center.longitude - buildingCenter.longitude) * mPerLng,
        y: (s.center.latitude - buildingCenter.latitude) * mPerLat,
      })),
    ];
    if (allM.length === 0) return 20;
    const maxR = Math.max(...allM.map((p) => Math.sqrt(p.x ** 2 + p.y ** 2)), 1);
    const halfSize = Math.max(
      ...roofSegmentStats.map((s) => Math.sqrt(s.stats.groundAreaMeters2) / 2),
      panelWidthMeters,
      panelHeightMeters,
      1
    );
    const drawR = Math.min(SVG_W, SVG_H) / 2 - PAD;
    return drawR / (maxR + halfSize);
  }, [activePanels, roofSegmentStats, buildingCenter, mPerLng, mPerLat, panelWidthMeters, panelHeightMeters]);

  const segmentData = useMemo(
    () =>
      roofSegmentStats.map((seg, i) => ({
        key: i,
        px: cx + (seg.center.longitude - buildingCenter.longitude) * mPerLng * scale,
        py: cy - (seg.center.latitude - buildingCenter.latitude) * mPerLat * scale,
        side: Math.sqrt(seg.stats.groundAreaMeters2) * scale,
        az: seg.azimuthDegrees,
        direction: getCardinal(seg.azimuthDegrees),
        style: SEGMENT_STYLES[i % SEGMENT_STYLES.length],
        segmentIndex: seg.segmentIndex,
      })),
    [roofSegmentStats, buildingCenter, mPerLng, mPerLat, scale, cx, cy]
  );

  const panelData = useMemo(
    () =>
      activePanels.map((panel, i) => {
        const seg = roofSegmentStats.find((s) => s.segmentIndex === panel.segmentIndex);
        const az = seg?.azimuthDegrees ?? 180;
        const isLandscape = panel.orientation === "LANDSCAPE";
        const pw = (isLandscape ? panelHeightMeters : panelWidthMeters) * scale;
        const ph = (isLandscape ? panelWidthMeters : panelHeightMeters) * scale;
        return {
          key: i,
          px: cx + (panel.center.longitude - buildingCenter.longitude) * mPerLng * scale,
          py: cy - (panel.center.latitude - buildingCenter.latitude) * mPerLat * scale,
          pw,
          ph,
          az,
          color: PANEL_COLORS[panel.segmentIndex % PANEL_COLORS.length],
        };
      }),
    [activePanels, roofSegmentStats, buildingCenter, mPerLng, mPerLat, scale, cx, cy, panelWidthMeters, panelHeightMeters]
  );

  return (
    <div className="rounded-lg overflow-hidden border border-gray-200">
      <svg
        viewBox={`0 0 ${SVG_W} ${SVG_H}`}
        width="100%"
        style={{ display: "block", background: "#f8fafc" }}
        aria-label="Roof schematic with solar panels"
      >
        {/* Subtle grid */}
        {Array.from({ length: 21 }, (_, i) => i - 10).map((i) => (
          <g key={i}>
            <line x1={0} y1={cy + i * 20} x2={SVG_W} y2={cy + i * 20} stroke="#e5e7eb" strokeWidth={0.4} />
            <line x1={cx + i * 20} y1={0} x2={cx + i * 20} y2={SVG_H} stroke="#e5e7eb" strokeWidth={0.4} />
          </g>
        ))}

        {/* Roof segments */}
        {segmentData.map((seg) => (
          <g key={seg.key} transform={`rotate(${seg.az + 180}, ${seg.px}, ${seg.py})`}>
            <rect
              x={seg.px - seg.side / 2}
              y={seg.py - seg.side / 2}
              width={seg.side}
              height={seg.side}
              fill={seg.style.fill}
              stroke={seg.style.stroke}
              strokeWidth={2}
              rx={3}
            />
            {/* Label counter-rotates so it's always readable */}
            <text
              x={seg.px}
              y={seg.py - seg.side / 2 + Math.max(14, seg.side * 0.18)}
              textAnchor="middle"
              fontSize={Math.min(13, Math.max(9, seg.side * 0.16))}
              fontWeight="600"
              fill={seg.style.text}
              transform={`rotate(${-(seg.az + 180)}, ${seg.px}, ${seg.py})`}
            >
              {seg.direction}-facing
            </text>
          </g>
        ))}

        {/* Solar panels */}
        {panelData.map((p) => (
          <g key={p.key} transform={`rotate(${p.az + 180}, ${p.px}, ${p.py})`}>
            <rect
              x={p.px - p.pw / 2}
              y={p.py - p.ph / 2}
              width={p.pw}
              height={p.ph}
              fill={p.color}
              fillOpacity={0.9}
              stroke="white"
              strokeWidth={0.6}
              rx={1}
            />
          </g>
        ))}

        {/* Compass rose — top right */}
        <CompassRose cx={SVG_W - 52} cy={52} r={26} />

        {/* Legend — bottom left */}
        <g>
          {segmentData.map((seg, i) => (
            <g key={i} transform={`translate(12, ${SVG_H - 14 - (segmentData.length - 1 - i) * 20})`}>
              <rect width={12} height={12} y={-11} fill={seg.style.fill} stroke={seg.style.stroke} strokeWidth={1.5} rx={2} />
              <rect width={6} height={10} x={3} y={-10} fill={PANEL_COLORS[i % PANEL_COLORS.length]} fillOpacity={0.9} rx={1} />
              <text x={18} y={0} fontSize={11} fill="#374151">
                Segment {seg.segmentIndex + 1} — {seg.direction}-facing
              </text>
            </g>
          ))}
        </g>
      </svg>
    </div>
  );
}
