'use client';

import React, { useState, useMemo } from 'react';
import {
  MapPin,
  CheckCircle2,
  AlertTriangle,
  ZoomIn,
  ZoomOut,
  RotateCcw,
  ChevronDown,
  Building,
  Users,
  Award
} from 'lucide-react';
import { StateItem, ScopeType, GeopoliticalZone } from '@/types';
import { NIGERIAN_STATES, GEOPOLITICAL_ZONES } from '@/lib/electoralData';

interface InteractiveNigeriaMapProps {
  userScopeType: ScopeType;
  userScopeId: string;
  selectedStateId?: string | null;
  onSelectState: (state: StateItem | null) => void;
  states?: StateItem[];
}

// Coordinate definitions for Nigeria's 36 States + FCT matching the official dashboard design (800x650 viewport)
const STATE_GEOMETRIES: {
  name: string;
  label: string;
  path: string;
  labelPos: [number, number];
}[] = [
  // NORTH WEST
  {
    name: 'Sokoto',
    label: 'Sokoto',
    labelPos: [175, 115],
    path: 'M 130 85 L 210 65 L 245 95 L 235 145 L 205 160 L 155 145 L 105 140 Z',
  },
  {
    name: 'Kebbi',
    label: 'Kebbi',
    labelPos: [110, 205],
    path: 'M 130 85 L 105 140 L 155 145 L 205 160 L 185 195 L 165 230 L 115 260 L 70 265 L 80 220 Z',
  },
  {
    name: 'Zamfara',
    label: 'Zamfara',
    labelPos: [215, 175],
    path: 'M 245 95 L 270 160 L 265 215 L 225 235 L 165 230 L 185 195 L 205 160 L 235 145 Z',
  },
  {
    name: 'Katsina',
    label: 'Katsina',
    labelPos: [300, 130],
    path: 'M 245 95 L 315 65 L 355 115 L 335 175 L 310 195 L 265 215 L 270 160 Z',
  },
  {
    name: 'Kano',
    label: 'Kano',
    labelPos: [365, 175],
    path: 'M 355 115 L 415 130 L 425 190 L 395 225 L 340 235 L 310 195 L 335 175 Z',
  },
  {
    name: 'Jigawa',
    label: 'Jigawa',
    labelPos: [430, 135],
    path: 'M 355 115 L 435 90 L 475 120 L 465 185 L 425 190 L 415 130 Z',
  },
  {
    name: 'Kaduna',
    label: 'Kaduna',
    labelPos: [320, 260],
    path: 'M 265 215 L 310 195 L 340 235 L 395 225 L 385 280 L 365 305 L 335 320 L 305 325 L 265 280 Z',
  },

  // NORTH EAST
  {
    name: 'Yobe',
    label: 'Yobe',
    labelPos: [525, 155],
    path: 'M 475 120 L 575 100 L 600 160 L 585 215 L 550 230 L 505 215 L 465 185 Z',
  },
  {
    name: 'Borno',
    label: 'Borno',
    labelPos: [665, 205],
    path: 'M 600 160 L 730 130 L 760 220 L 705 290 L 645 280 L 610 260 L 550 230 L 585 215 Z',
  },
  {
    name: 'Bauchi',
    label: 'Bauchi',
    labelPos: [445, 245],
    path: 'M 395 225 L 425 190 L 465 185 L 505 215 L 505 275 L 475 295 L 415 285 L 385 280 Z',
  },
  {
    name: 'Gombe',
    label: 'Gombe',
    labelPos: [545, 265],
    path: 'M 505 215 L 550 230 L 610 260 L 585 310 L 555 315 L 505 310 L 475 295 L 505 275 Z',
  },
  {
    name: 'Adamawa',
    label: 'Adamawa',
    labelPos: [635, 335],
    path: 'M 610 260 L 645 280 L 705 290 L 695 355 L 665 415 L 615 385 L 585 350 L 585 310 Z',
  },
  {
    name: 'Taraba',
    label: 'Taraba',
    labelPos: [550, 405],
    path: 'M 505 310 L 555 315 L 585 350 L 615 385 L 665 415 L 610 465 L 565 495 L 490 445 L 475 410 L 465 345 Z',
  },

  // NORTH CENTRAL
  {
    name: 'Niger',
    label: 'Niger',
    labelPos: [205, 310],
    path: 'M 115 260 L 165 230 L 225 235 L 265 215 L 265 280 L 305 325 L 295 360 L 265 395 L 210 385 L 175 365 Z',
  },
  {
    name: 'FCT',
    label: 'FCT',
    labelPos: [320, 345],
    path: 'M 305 325 L 335 320 L 350 345 L 335 370 L 305 365 L 295 360 Z',
  },
  {
    name: 'Plateau',
    label: 'Plateau',
    labelPos: [420, 335],
    path: 'M 385 280 L 415 285 L 475 295 L 465 345 L 445 385 L 395 375 L 365 350 L 365 305 Z',
  },
  {
    name: 'Nasarawa',
    label: 'Nasarawa',
    labelPos: [385, 385],
    path: 'M 335 320 L 365 305 L 365 350 L 395 375 L 445 385 L 435 420 L 395 425 L 340 420 L 335 370 L 350 345 Z',
  },
  {
    name: 'Benue',
    label: 'Benue',
    labelPos: [435, 455],
    path: 'M 340 420 L 395 425 L 435 420 L 475 410 L 490 445 L 565 495 L 505 505 L 465 500 L 415 485 L 375 480 L 340 455 Z',
  },
  {
    name: 'Kogi',
    label: 'Kogi',
    labelPos: [300, 440],
    path: 'M 265 395 L 295 360 L 305 365 L 335 370 L 340 420 L 340 455 L 375 480 L 340 495 L 295 495 L 265 480 L 245 450 L 255 435 Z',
  },
  {
    name: 'Kwara',
    label: 'Kwara',
    labelPos: [180, 400],
    path: 'M 115 260 L 175 365 L 210 385 L 265 395 L 255 435 L 225 445 L 195 435 L 155 425 L 110 390 Z',
  },

  // SOUTH WEST
  {
    name: 'Oyo',
    label: 'Oyo',
    labelPos: [135, 455],
    path: 'M 110 390 L 155 425 L 195 435 L 185 475 L 165 495 L 125 495 L 95 485 L 90 440 Z',
  },
  {
    name: 'Osun',
    label: 'Osun',
    labelPos: [190, 465],
    path: 'M 195 435 L 215 435 L 225 465 L 205 495 L 165 495 L 185 475 Z',
  },
  {
    name: 'Ekiti',
    label: 'Ekiti',
    labelPos: [230, 455],
    path: 'M 215 435 L 245 450 L 245 480 L 225 465 Z',
  },
  {
    name: 'Ondo',
    label: 'Ondo',
    labelPos: [220, 505],
    path: 'M 225 465 L 245 480 L 265 480 L 260 520 L 245 545 L 180 545 L 185 515 L 205 495 Z',
  },
  {
    name: 'Ogun',
    label: 'Ogun',
    labelPos: [135, 510],
    path: 'M 95 485 L 125 495 L 165 495 L 205 495 L 185 515 L 180 545 L 185 535 L 120 525 L 115 535 L 85 520 Z',
  },
  {
    name: 'Lagos',
    label: 'Lagos',
    labelPos: [145, 540],
    path: 'M 115 535 L 185 535 L 180 545 L 145 550 L 110 545 Z',
  },

  // SOUTH SOUTH
  {
    name: 'Edo',
    label: 'Edo',
    labelPos: [275, 510],
    path: 'M 265 480 L 295 495 L 295 535 L 270 550 L 245 545 L 260 520 Z',
  },
  {
    name: 'Delta',
    label: 'Delta',
    labelPos: [275, 570],
    path: 'M 245 545 L 270 550 L 295 535 L 310 550 L 305 580 L 275 585 L 255 605 Z',
  },
  {
    name: 'Bayelsa',
    label: 'Bayelsa',
    labelPos: [285, 605],
    path: 'M 275 585 L 305 580 L 325 615 L 290 625 L 255 605 Z',
  },
  {
    name: 'Rivers',
    label: 'Rivers',
    labelPos: [335, 585],
    path: 'M 310 550 L 335 555 L 365 560 L 375 585 L 365 615 L 325 615 L 305 580 Z',
  },
  {
    name: 'Akwa Ibom',
    label: 'Akwa Ibom',
    labelPos: [395, 585],
    path: 'M 365 560 L 395 565 L 425 570 L 430 585 L 410 610 L 375 585 Z',
  },
  {
    name: 'Cross River',
    label: 'Cross River',
    labelPos: [445, 525],
    path: 'M 465 470 L 465 500 L 455 560 L 430 585 L 425 570 L 395 565 L 410 530 L 425 505 Z',
  },

  // SOUTH EAST
  {
    name: 'Anambra',
    label: 'Anambra',
    labelPos: [315, 520],
    path: 'M 295 495 L 340 495 L 335 530 L 315 550 L 310 550 L 295 535 Z',
  },
  {
    name: 'Enugu',
    label: 'Enugu',
    labelPos: [365, 505],
    path: 'M 340 495 L 375 480 L 395 480 L 390 520 L 365 530 L 335 530 Z',
  },
  {
    name: 'Ebonyi',
    label: 'Ebonyi',
    labelPos: [415, 505],
    path: 'M 395 480 L 415 485 L 465 500 L 425 505 L 410 530 L 385 535 L 390 520 Z',
  },
  {
    name: 'Imo',
    label: 'Imo',
    labelPos: [330, 545],
    path: 'M 315 550 L 335 530 L 350 555 L 335 555 L 310 550 Z',
  },
  {
    name: 'Abia',
    label: 'Abia',
    labelPos: [375, 545],
    path: 'M 365 530 L 385 535 L 410 530 L 395 565 L 365 560 L 350 555 L 335 530 Z',
  },
];

export function InteractiveNigeriaMap({
  userScopeType,
  userScopeId,
  selectedStateId,
  onSelectState,
  states,
}: InteractiveNigeriaMapProps) {
  const [hoveredStateName, setHoveredStateName] = useState<string | null>(null);
  const [zoomScale, setZoomScale] = useState<number>(1);

  const statesDataSource = states || NIGERIAN_STATES;

  // Match state by name (handling FCT vs FCT Abuja)
  const findStateObj = (name: string): StateItem | undefined => {
    return statesDataSource.find(
      (s) =>
        s.name.toLowerCase() === name.toLowerCase() ||
        (name === 'FCT' && s.id === '37') ||
        (name === 'FCT' && s.name.toLowerCase().includes('fct'))
    );
  };

  // Downward Scope Filter: Enforce supervisor jurisdiction locking
  const isStateAllowed = (state: StateItem) => {
    if (userScopeType === 'NATIONAL') return true;

    if (userScopeType === 'REGION') {
      return state.geopolitical_zone === userScopeId;
    }

    if (userScopeType === 'STATE') {
      return state.id === userScopeId || state.name.toLowerCase() === userScopeId.toLowerCase();
    }

    if (userScopeType === 'LGA' || userScopeType === 'WARD') {
      const stateId = userScopeId.slice(0, 2);
      return state.id === stateId;
    }

    return true;
  };

  // Determine leading party and color for each state
  // Colors match user's uploaded dashboard: Emerald Green for ADC (Leading), Blue for PDP, Red for LP
  const getStateColor = (state: StateItem | undefined, isAllowed: boolean) => {
    if (!isAllowed || !state) return '#93c5fd';

    const votes = state.votes || {};
    const adcVotes = votes.ADC || 0;
    const ndcVotes = votes.NDC || 0;
    const apcVotes = votes.APC || 0;
    const pdpVotes = votes.PDP || 0;
    const lpVotes = votes.LP || 0;

    const maxVotes = Math.max(adcVotes, ndcVotes, apcVotes, pdpVotes, lpVotes);
    if (maxVotes > 0) {
      if (maxVotes === adcVotes) return '#15803d'; // Emerald green (ADC - Leading)
      if (maxVotes === ndcVotes) return '#0891b2'; // Cyan/Teal (NDC - Leading)
      if (maxVotes === apcVotes) return '#16a34a'; // APC green
      if (maxVotes === pdpVotes) return '#2563eb'; // PDP royal blue
      if (maxVotes === lpVotes) return '#dc2626';  // LP red
    }

    // Default state: Patriotic Nigerian Ocean/Royal Blue cleanly matching white background
    return '#1d4ed8';
  };

  const activeStateObject = useMemo(() => {
    if (!selectedStateId) return null;
    return NIGERIAN_STATES.find((s) => s.id === selectedStateId) || null;
  }, [selectedStateId]);

  const hoveredStateObject = useMemo(() => {
    if (!hoveredStateName) return null;
    return findStateObj(hoveredStateName) || null;
  }, [hoveredStateName]);

  return (
    <div className="bg-white rounded-xl border border-slate-200/90 p-4 shadow-xs flex flex-col justify-between">
      {/* Top Map Card Controls matching Mockup */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between pb-3 border-b border-slate-100 gap-3">
        <div>
          <h3 className="text-sm font-black text-slate-900 tracking-tight">
            Geopolitical Collation Map
          </h3>
          <p className="text-[11px] text-slate-500 font-medium">
            36 States + FCT Federal Capital Territory
          </p>
        </div>

        <div className="flex items-center space-x-2">
          {/* State Dropdown Selector */}
          <div className="relative">
            <select
              value={selectedStateId || ''}
              onChange={(e) => {
                const val = e.target.value;
                if (!val) {
                  onSelectState(null);
                } else {
                  const st = NIGERIAN_STATES.find((s) => s.id === val);
                  if (st) onSelectState(st);
                }
              }}
              className="appearance-none bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 text-xs font-bold py-1.5 pl-3 pr-7 rounded-lg cursor-pointer focus:outline-none focus:ring-1 focus:ring-emerald-500"
            >
              <option value="">All 36 States + FCT</option>
              {NIGERIAN_STATES.map((st) => (
                <option key={st.id} value={st.id} disabled={!isStateAllowed(st)}>
                  {st.name} State {st.id === '19' ? '★ (Kaduna)' : ''}
                </option>
              ))}
            </select>
            <ChevronDown className="w-3.5 h-3.5 text-slate-400 absolute right-2 top-2.5 pointer-events-none" />
          </div>

          {/* Zoom Buttons */}
          <div className="flex items-center border border-slate-200 rounded-lg overflow-hidden bg-slate-50">
            <button
              onClick={() => setZoomScale((prev) => Math.min(prev + 0.2, 1.8))}
              className="p-1.5 hover:bg-slate-200 text-slate-600 transition-colors"
              title="Zoom In"
            >
              <ZoomIn className="w-3.5 h-3.5" />
            </button>
            <button
              onClick={() => setZoomScale((prev) => Math.max(prev - 0.2, 0.8))}
              className="p-1.5 hover:bg-slate-200 text-slate-600 border-l border-slate-200 transition-colors"
              title="Zoom Out"
            >
              <ZoomOut className="w-3.5 h-3.5" />
            </button>
            <button
              onClick={() => {
                setZoomScale(1);
                onSelectState(null);
              }}
              className="p-1.5 hover:bg-slate-200 text-slate-600 border-l border-slate-200 transition-colors"
              title="Reset View"
            >
              <RotateCcw className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>
      </div>

      {/* SVG Map Container (Exact Normalized Viewport 0 0 800 650) */}
      <div className="relative my-2 w-full h-[340px] sm:h-[400px] flex items-center justify-center overflow-hidden bg-gradient-to-b from-blue-50/50 via-white to-slate-50/80 rounded-2xl border border-blue-100/80 shadow-inner">
        <svg
          viewBox="0 0 800 650"
          className="w-full h-full transition-transform duration-300 ease-out"
          style={{ transform: `scale(${zoomScale})` }}
          onMouseLeave={() => setHoveredStateName(null)}
        >
          {/* Render All 37 State Polygons */}
          <g className="transition-all duration-200">
            {STATE_GEOMETRIES.map((geom) => {
              const stateObj = findStateObj(geom.name);
              const isAllowed = stateObj ? isStateAllowed(stateObj) : true;
              const isSelected = selectedStateId && stateObj ? selectedStateId === stateObj.id : false;
              const isHovered = hoveredStateName === geom.name;
              const fillColor = getStateColor(stateObj, isAllowed);

              return (
                <g
                  key={geom.name}
                  className="cursor-pointer group"
                  onClick={() => {
                    if (stateObj && isAllowed) {
                      onSelectState(isSelected ? null : stateObj);
                    }
                  }}
                  onMouseEnter={() => setHoveredStateName(geom.name)}
                >
                  <path
                    d={geom.path}
                    fill={fillColor}
                    stroke={isSelected ? '#F59E0B' : '#FFFFFF'}
                    strokeWidth={isSelected ? '3.5' : '1.8'}
                    strokeLinejoin="round"
                    strokeLinecap="round"
                    vectorEffect="non-scaling-stroke"
                    fillOpacity={isSelected ? 1 : isHovered ? 0.95 : 0.92}
                    className="transition-all hover:filter hover:brightness-110 drop-shadow-xs"
                  />

                  {/* Clean State Name Text Label */}
                  <text
                    x={geom.labelPos[0]}
                    y={geom.labelPos[1]}
                    textAnchor="middle"
                    dominantBaseline="middle"
                    fill="#FFFFFF"
                    fontSize={geom.name.length > 7 ? '9' : '10'}
                    fontWeight="800"
                    pointerEvents="none"
                    className="select-none drop-shadow-[0_1px_2px_rgba(0,0,0,0.85)]"
                  >
                    {geom.label}
                  </text>
                </g>
              );
            })}
          </g>
        </svg>

        {/* Selected or Hovered State Floating Pill Badge */}
        {(activeStateObject || hoveredStateObject) && (
          <div className="absolute top-2 left-2 bg-white/95 backdrop-blur-md border border-slate-200/90 px-3.5 py-2 rounded-xl shadow-lg text-xs font-bold text-slate-900 flex items-center space-x-2 animate-fadeIn">
            <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse" />
            <span className="font-extrabold text-slate-950">
              {activeStateObject?.name || hoveredStateObject?.name} State
            </span>
            <span className="text-[11px] text-blue-700 font-mono font-semibold">
              ({(activeStateObject?.registered_voters || hoveredStateObject?.registered_voters || 0).toLocaleString()} Registered Voters &bull; {activeStateObject?.total_pus || hoveredStateObject?.total_pus || 0} PUs)
            </span>
          </div>
        )}
      </div>

      {/* Map Legend: Matching White Background Palette */}
      <div className="pt-3 border-t border-slate-100 flex flex-wrap items-center justify-between gap-3 text-xs">
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center space-x-1.5">
            <span className="w-3 h-3 rounded-full bg-[#15803d] shadow-2xs" />
            <span className="font-bold text-slate-800">ADC (Leading)</span>
          </div>
          <div className="flex items-center space-x-1.5">
            <span className="w-3 h-3 rounded-full bg-[#0891b2] shadow-2xs" />
            <span className="font-bold text-slate-800">NDC (Leading)</span>
          </div>
          <div className="flex items-center space-x-1.5">
            <span className="w-3 h-3 rounded-full bg-[#2563eb] shadow-2xs" />
            <span className="font-semibold text-slate-700">PDP (Leading)</span>
          </div>
          <div className="flex items-center space-x-1.5">
            <span className="w-3 h-3 rounded-full bg-[#dc2626] shadow-2xs" />
            <span className="font-semibold text-slate-700">LP (Leading)</span>
          </div>
          <div className="flex items-center space-x-1.5">
            <span className="w-3 h-3 rounded-full bg-[#1d4ed8] shadow-2xs" />
            <span className="font-medium text-slate-600">Collation Standby</span>
          </div>
        </div>

        <div className="text-[11px] text-slate-400 font-mono">
          Click state to zoom &amp; inspect returns
        </div>
      </div>
    </div>
  );
}
