'use client';

import React, { useMemo } from 'react';
import {
  Globe2,
  Users,
  Award,
  CheckCircle2,
  TrendingUp,
  Download,
  Printer,
  ShieldCheck,
  Building
} from 'lucide-react';
import { NIGERIAN_STATES } from '@/lib/electoralData';
import { ScopeType, StateItem } from '@/types';

interface ZoneSummary {
  name: string;
  code: string;
  statesCount: number;
  statesList: string[];
  totalRegistered: number;
  totalPus: number;
  adcVotes: number;
  apcVotes: number;
  pdpVotes: number;
  lpVotes: number;
  totalValid: number;
  leadMargin: number;
  winner: string;
  thresholdMetCount: number;
  zonalDirector: string;
}

interface RegionalSummaryViewProps {
  userScopeType?: ScopeType;
  userScopeId?: string;
  states?: StateItem[];
}

export function RegionalSummaryView({ userScopeType, userScopeId, states }: RegionalSummaryViewProps = {}) {
  const currentStates = states || NIGERIAN_STATES;

  const zoneCodeToName: Record<string, string> = {
    NORTH_WEST: 'North West',
    NORTH_EAST: 'North East',
    NORTH_CENTRAL: 'North Central',
    SOUTH_WEST: 'South West',
    SOUTH_EAST: 'South East',
    SOUTH_SOUTH: 'South South',
  };

  const zonesData: ZoneSummary[] = useMemo(() => {
    let zonesConfig = [
      { name: 'North West', code: 'NW', director: 'Sen. Rabiu Kwankwaso / Dr. Aminu Tambuwal' },
      { name: 'North East', code: 'NE', director: 'H.E. Governor Ahmadu Fintiri / H.E. Bala Mohammed' },
      { name: 'North Central', code: 'NC', director: 'Sen. Bukola Saraki / Chief Gabriel Suswam' },
      { name: 'South West', code: 'SW', director: 'Engr. Seyi Makinde / Dr. Ralph Nwosu' },
      { name: 'South East', code: 'SE', director: 'H.E. Peter Obi / Sen. Adolphus Wabara' },
      { name: 'South South', code: 'SS', director: 'H.E. Nyesom Wike / H.E. Douye Diri' },
    ];

    if (userScopeType === 'REGION' && userScopeId) {
      const expectedZoneName = zoneCodeToName[userScopeId] || userScopeId;
      zonesConfig = zonesConfig.filter((z) => z.name === expectedZoneName || z.code === userScopeId);
    } else if ((userScopeType === 'STATE' || userScopeType === 'LGA' || userScopeType === 'WARD' || userScopeType === 'PU') && userScopeId) {
      const stateId = userScopeId.split('-')[0];
      const targetState = currentStates.find(s => s.id === stateId);
      if (targetState) {
        zonesConfig = zonesConfig.filter((z) => z.name === targetState.geopolitical_zone);
      }
    }

    return zonesConfig.map((config) => {
      const statesInZone = currentStates.filter((s) => s.geopolitical_zone === config.name);
      const statesCount = statesInZone.length;
      const statesList = statesInZone.map((s) => s.name);
      const totalRegistered = statesInZone.reduce((sum, s) => sum + s.registered_voters, 0);
      const totalPus = statesInZone.reduce((sum, s) => sum + s.total_pus, 0);

      const adcVotes = statesInZone.reduce((sum, s) => sum + (s.votes?.ADC || 0), 0);
      const apcVotes = statesInZone.reduce((sum, s) => sum + (s.votes?.APC || 0), 0);
      const pdpVotes = statesInZone.reduce((sum, s) => sum + (s.votes?.PDP || 0), 0);
      const lpVotes = statesInZone.reduce((sum, s) => sum + (s.votes?.LP || 0), 0);

      const totalValid = adcVotes + apcVotes + pdpVotes + lpVotes;
      const leadMargin = adcVotes - apcVotes;
      const winner = adcVotes > apcVotes ? 'ADC' : apcVotes > adcVotes ? 'APC' : 'TIE';

      const thresholdMetCount = statesInZone.filter((s) => {
        const total = (s.votes?.ADC || 0) + (s.votes?.APC || 0) + (s.votes?.PDP || 0) + (s.votes?.LP || 0);
        return total > 0 && (s.votes?.ADC || 0) / total >= 0.25;
      }).length;

      return {
        name: config.name,
        code: config.code,
        statesCount,
        statesList,
        totalRegistered,
        totalPus,
        adcVotes,
        apcVotes,
        pdpVotes,
        lpVotes,
        totalValid,
        leadMargin,
        winner,
        thresholdMetCount,
        zonalDirector: config.director,
      };
    });
  }, [currentStates, userScopeId, userScopeType]);

  // National Summary Totals
  const nationalTotals = useMemo(() => {
    const totalReg = zonesData.reduce((acc, z) => acc + z.totalRegistered, 0);
    const totalAdc = zonesData.reduce((acc, z) => acc + z.adcVotes, 0);
    const totalApc = zonesData.reduce((acc, z) => acc + z.apcVotes, 0);
    const totalPdp = zonesData.reduce((acc, z) => acc + z.pdpVotes, 0);
    const totalLp = zonesData.reduce((acc, z) => acc + z.lpVotes, 0);
    const totalValid = totalAdc + totalApc + totalPdp + totalLp;

    return {
      totalReg,
      totalAdc,
      totalApc,
      totalPdp,
      totalLp,
      totalValid,
      leadMargin: totalAdc - totalApc,
      adcSharePct: totalValid > 0 ? ((totalAdc / totalValid) * 100).toFixed(1) : '0.0',
    };
  }, [zonesData]);

  const handleExportCsv = () => {
    const headers = [
      'Geopolitical_Zone',
      'Zone_Code',
      'States_Count',
      'States_List',
      'Total_Registered_Voters',
      'Total_Polling_Units',
      'ADC_Votes_Atiku',
      'APC_Votes_Tinubu',
      'PDP_Votes',
      'LP_Votes_Obi',
      'Total_Valid_Votes',
      'ADC_Vote_Share_Pct',
      'Zone_Lead_Margin',
      '25_Pct_Threshold_States_Met',
      'Zonal_Command_Director',
    ];

    const rows = zonesData.map((z) => {
      const pct = z.totalValid > 0 ? ((z.adcVotes / z.totalValid) * 100).toFixed(1) : '0.0';
      return [
        `"${z.name}"`,
        z.code,
        z.statesCount,
        `"${z.statesList.join(', ')}"`,
        z.totalRegistered,
        z.totalPus,
        z.adcVotes,
        z.apcVotes,
        z.pdpVotes,
        z.lpVotes,
        z.totalValid,
        `${pct}%`,
        z.leadMargin,
        `${z.thresholdMetCount}/${z.statesCount}`,
        `"${z.zonalDirector}"`,
      ].join(',');
    });

    const csvText = '\uFEFF' + [headers.join(','), ...rows].join('\n');
    const blob = new Blob([csvText], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `INEC_ZONE_BY_ZONE_SUMMARY_${Date.now()}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6 text-slate-900 font-sans">
      {/* View Header */}
      <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center space-x-2">
            <span className="p-2 rounded-lg bg-emerald-100 text-emerald-800 font-bold">
              <Globe2 className="w-5 h-5" />
            </span>
            <h1 className="text-xl font-black text-emerald-950 tracking-tight">
              Zone-by-Zone Geopolitical Command Summary
            </h1>
          </div>
          <p className="text-xs text-slate-600 mt-1">
            Zone by Zone Performance Analysis across Nigeria's 6 Geopolitical Zones • ADC Joint Alliance Command
          </p>
        </div>

        <div className="flex items-center space-x-2">
          <button
            onClick={handleExportCsv}
            className="px-3.5 py-2 rounded-xl bg-emerald-700 hover:bg-emerald-800 text-white text-xs font-bold flex items-center space-x-1.5 shadow transition"
          >
            <Download className="w-4 h-4" />
            <span>Export Zone by Zone CSV</span>
          </button>
          <button
            onClick={() => window.print()}
            className="px-3.5 py-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold flex items-center space-x-1.5 shadow transition"
          >
            <Printer className="w-4 h-4" />
            <span>Print Zonal Dossier</span>
          </button>
        </div>
      </div>

      {/* National Zonal Benchmark Banner */}
      <div className="bg-gradient-to-r from-emerald-800 to-emerald-900 text-white p-5 rounded-2xl shadow-md flex flex-col md:flex-row items-center justify-between gap-4">
        <div>
          <span className="text-[10px] font-black uppercase text-amber-300 tracking-widest block">
            NATIONAL GEOPOLITICAL OVERVIEW
          </span>
          <h2 className="text-lg font-black text-white mt-0.5">
            {nationalTotals.totalValid > 0
              ? `ADC Coalition Leads in ${zonesData.filter(z => z.winner === 'ADC' && z.totalValid > 0).length} of 6 Geopolitical Zones`
              : 'Live Geopolitical Collation • Standing By'}
          </h2>
          <p className="text-xs text-emerald-100 mt-1">
            {nationalTotals.totalValid > 0
              ? 'Performance tracking across North West, North East, North Central, South South, South West, and South East regions.'
              : 'Awaiting certified polling unit transmissions across Nigeria\'s 6 geopolitical zones.'}
          </p>
        </div>

        <div className="flex items-center space-x-6 text-center font-mono border-t md:border-t-0 md:border-l border-emerald-700/60 pt-3 md:pt-0 md:pl-6">
          <div>
            <span className="text-[10px] text-emerald-200 block">TOTAL VALID VOTES</span>
            <span className="text-lg font-black text-white">{nationalTotals.totalValid.toLocaleString()}</span>
          </div>
          <div>
            <span className="text-[10px] text-amber-300 block">NATIONAL SHARE</span>
            <span className="text-lg font-black text-amber-300">{nationalTotals.adcSharePct}%</span>
          </div>
        </div>
      </div>

      {/* 6 Geopolitical Zone Cards Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        {zonesData.map((zone) => {
          const isWinner = zone.winner === 'ADC' && zone.totalValid > 0;
          const voteSharePct = zone.totalValid > 0 ? ((zone.adcVotes / zone.totalValid) * 100).toFixed(1) : '0.0';

          return (
            <div
              key={zone.code}
              className={`bg-white border rounded-2xl p-5 shadow-xs flex flex-col justify-between transition hover:shadow-md ${
                isWinner ? 'border-emerald-300 bg-gradient-to-b from-emerald-50/30 to-white' : 'border-slate-200'
              }`}
            >
              <div>
                {/* Zone Card Header */}
                <div className="flex items-center justify-between border-b border-slate-200 pb-3 mb-3">
                  <div>
                    <div className="flex items-center space-x-2">
                      <span className="px-2 py-0.5 rounded-md bg-emerald-600 text-white font-mono font-black text-xs">
                        {zone.code}
                      </span>
                      <h3 className="text-base font-black text-slate-900 tracking-tight">
                        {zone.name} Zone
                      </h3>
                    </div>
                    <p className="text-[11px] text-slate-500 mt-0.5">
                      {zone.statesCount} States ({zone.statesList.join(', ')})
                    </p>
                  </div>
                  {zone.totalValid === 0 ? (
                    <span className="px-2.5 py-1 rounded-lg bg-slate-100 text-slate-600 text-[10px] font-bold uppercase font-mono">
                      Awaiting Collation
                    </span>
                  ) : isWinner ? (
                    <span className="px-2.5 py-1 rounded-lg bg-emerald-600 text-white text-[10px] font-black uppercase shadow-xs">
                      ADC Lead
                    </span>
                  ) : (
                    <span className="px-2.5 py-1 rounded-lg bg-slate-200 text-slate-700 text-[10px] font-bold uppercase">
                      APC Lead
                    </span>
                  )}
                </div>

                {/* Key Zonal Numbers */}
                <div className="grid grid-cols-2 gap-3 bg-slate-50 p-3 rounded-xl border border-slate-200 font-mono text-xs mb-4">
                  <div>
                    <span className="text-[9px] text-slate-500 block uppercase">Reg. Voters</span>
                    <span className="font-bold text-slate-900">{zone.totalRegistered.toLocaleString()}</span>
                  </div>
                  <div>
                    <span className="text-[9px] text-slate-500 block uppercase">Polling Units</span>
                    <span className="font-bold text-slate-900">{zone.totalPus.toLocaleString()}</span>
                  </div>
                  <div>
                    <span className="text-[9px] text-slate-500 block uppercase">ADC Votes (Atiku)</span>
                    <span className="font-black text-emerald-800 text-sm">{zone.adcVotes.toLocaleString()}</span>
                  </div>
                  <div>
                    <span className="text-[9px] text-slate-500 block uppercase">APC Votes (Tinubu)</span>
                    <span className="font-bold text-slate-700">{zone.apcVotes.toLocaleString()}</span>
                  </div>
                </div>

                {/* 25% Threshold & Margin Metrics */}
                <div className="space-y-2 text-xs mb-4">
                  <div className="flex items-center justify-between p-2 rounded-lg bg-emerald-50/80 border border-emerald-200">
                    <span className="text-emerald-900 font-semibold text-[11px]">25% Threshold Met:</span>
                    <span className="font-mono font-bold text-emerald-800">
                      {zone.thresholdMetCount} / {zone.statesCount} States
                    </span>
                  </div>

                  <div className="flex items-center justify-between p-2 rounded-lg bg-slate-50 border border-slate-200">
                    <span className="text-slate-700 font-semibold text-[11px]">ADC Vote Share:</span>
                    <span className="font-mono font-bold text-slate-900">{voteSharePct}%</span>
                  </div>
                </div>
              </div>

              {/* Zonal Command Director */}
              <div className="border-t border-slate-200 pt-3 text-[11px]">
                <span className="text-[9px] font-bold uppercase text-slate-400 block tracking-wider">
                  ZONAL COMMAND DIRECTORS
                </span>
                <p className="font-bold text-slate-800 truncate mt-0.5">
                  {zone.zonalDirector}
                </p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
