'use client';

import React, { useState, useMemo } from 'react';
import {
  Map,
  Search,
  Filter,
  Download,
  Printer,
  CheckCircle2,
  AlertTriangle,
  Building,
  TrendingUp,
  Award,
  ChevronDown
} from 'lucide-react';
import { NIGERIAN_STATES } from '@/lib/electoralData';
import { ScopeType, StateItem } from '@/types';

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

export function StateByStateReportView({
  userScopeType,
  userScopeId,
  states = NIGERIAN_STATES,
}: StateByStateReportViewProps = {}) {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedZone, setSelectedZone] = useState<string>('ALL');
  const [sortBy, setSortBy] = useState<'VOTES' | 'MARGIN' | 'TURNOUT' | 'NAME'>('VOTES');

  // Map zone code to full name
  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',
  };

  // Filter and sort states
  const filteredStates = useMemo(() => {
    return states.filter((state) => {
      // Scope lock filtering
      if (userScopeType === 'STATE' && userScopeId && state.id !== userScopeId) {
        return false;
      }
      if (userScopeType === 'REGION' && userScopeId) {
        const expectedZone = zoneCodeToName[userScopeId] || userScopeId;
        if (state.geopolitical_zone !== expectedZone) return false;
      }
      if (userScopeType === 'LGA' && userScopeId) {
        const stateIdFromLga = userScopeId.split('-')[0];
        if (state.id !== stateIdFromLga) return false;
      }
      if (userScopeType === 'WARD' && userScopeId) {
        const stateIdFromWard = userScopeId.split('-')[0];
        if (state.id !== stateIdFromWard) return false;
      }
      if (userScopeType === 'PU' && userScopeId) {
        const stateIdFromPu = userScopeId.split('-')[0];
        if (state.id !== stateIdFromPu) return false;
      }

      const matchesSearch =
        state.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        state.id.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesZone = selectedZone === 'ALL' || state.geopolitical_zone === selectedZone;
      return matchesSearch && matchesZone;
    }).sort((a, b) => {
      const aAdc = a.votes?.ADC || 0;
      const bAdc = b.votes?.ADC || 0;
      const aApc = a.votes?.APC || 0;
      const bApc = b.votes?.APC || 0;

      if (sortBy === 'VOTES') return bAdc - aAdc;
      if (sortBy === 'MARGIN') return (bAdc - bApc) - (aAdc - aApc);
      if (sortBy === 'TURNOUT') return b.registered_voters - a.registered_voters;
      return a.name.localeCompare(b.name);
    });
  }, [states, searchTerm, selectedZone, sortBy, userScopeType, userScopeId]);

  // Overall Statistics across 37 States
  const stats = useMemo(() => {
    const totalStates = states.length;
    const statesWonByAdc = states.filter((s) => {
      const adc = s.votes?.ADC || 0;
      const apc = s.votes?.APC || 0;
      return (adc > 0 || apc > 0) && adc > apc;
    }).length;
    const statesMeeting25Percent = states.filter((s) => {
      const adc = s.votes?.ADC || 0;
      const total = (s.votes?.ADC || 0) + (s.votes?.APC || 0) + (s.votes?.PDP || 0) + (s.votes?.LP || 0);
      return total > 0 && adc / total >= 0.25;
    }).length;
    const totalAdcVotes = states.reduce((acc, s) => acc + (s.votes?.ADC || 0), 0);
    const totalApcVotes = states.reduce((acc, s) => acc + (s.votes?.APC || 0), 0);
    const hasAnyVotes = totalAdcVotes > 0 || totalApcVotes > 0;

    return {
      totalStates,
      statesWonByAdc,
      statesMeeting25Percent,
      totalAdcVotes,
      totalApcVotes,
      nationalLeadMargin: totalAdcVotes - totalApcVotes,
      hasAnyVotes,
    };
  }, [states]);

  const handleExportCsv = () => {
    const headers = [
      'State_Code',
      'State_Name',
      'Geopolitical_Zone',
      'Registered_Voters',
      'Total_LGAs',
      'PUs_Reported',
      'ADC_Votes_Atiku',
      'APC_Votes_Tinubu',
      'PDP_Votes',
      'LP_Votes_Obi',
      'Total_Valid_Votes',
      'ADC_Vote_Share_Pct',
      'Passes_25_Pct_Threshold',
      'State_Winner',
      'Form_EC8D_Certified',
    ];

    const rows = filteredStates.map((s) => {
      const adc = s.votes?.ADC || 0;
      const apc = s.votes?.APC || 0;
      const pdp = s.votes?.PDP || 0;
      const lp = s.votes?.LP || 0;
      const valid = adc + apc + pdp + lp;
      const pct = valid > 0 ? ((adc / valid) * 100).toFixed(1) : '0.0';
      const passes25 = valid > 0 && adc / valid >= 0.25 ? 'YES' : 'NO';
      const winner = adc > apc ? 'ADC (Atiku Abubakar)' : apc > adc ? 'APC (Tinubu)' : 'TIE';

      return [
        s.id,
        `"${s.name}"`,
        s.geopolitical_zone,
        s.registered_voters,
        s.total_lgas,
        s.pus_reported || s.total_pus,
        adc,
        apc,
        pdp,
        lp,
        valid,
        `${pct}%`,
        passes25,
        `"${winner}"`,
        'YES_CERTIFIED',
      ].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_STATE_BY_STATE_REPORT_${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">
              <Map className="w-5 h-5" />
            </span>
            <h1 className="text-xl font-black text-emerald-950 tracking-tight">
              State-by-State Executive Analytical Report
            </h1>
          </div>
          <p className="text-xs text-slate-600 mt-1">
            Complete Electoral Audit across 36 States + FCT Abuja • Certified Form EC8D State Collation Records
          </p>
        </div>

        {/* Action Controls */}
        <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 State 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 Report</span>
          </button>
        </div>
      </div>

      {/* Top 4 Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white border border-slate-200 p-4 rounded-2xl shadow-xs">
          <span className="text-[10px] font-bold uppercase text-slate-500 tracking-wider">
            Total States Analyzed
          </span>
          <div className="text-2xl font-black text-slate-900 mt-1">
            {stats.totalStates} <span className="text-xs font-normal text-slate-500">(36 + FCT)</span>
          </div>
          <p className="text-[11px] text-emerald-700 font-semibold mt-1">
            {stats.hasAnyVotes ? '100% EC8D Certified' : 'Registered Voters Baseline'}
          </p>
        </div>

        <div className="bg-white border border-emerald-200 p-4 rounded-2xl shadow-xs bg-gradient-to-br from-emerald-50/50 to-white">
          <span className="text-[10px] font-bold uppercase text-emerald-800 tracking-wider">
            States Won (ADC Lead)
          </span>
          <div className="text-2xl font-black text-emerald-800 mt-1">
            {stats.statesWonByAdc} <span className="text-xs font-normal text-emerald-700">/ 37</span>
          </div>
          <p className="text-[11px] text-emerald-800 font-bold mt-1">
            {stats.hasAnyVotes ? 'Simple Majority Lead' : 'Awaiting Collation'}
          </p>
        </div>

        <div className="bg-white border border-amber-200 p-4 rounded-2xl shadow-xs bg-gradient-to-br from-amber-50/50 to-white">
          <span className="text-[10px] font-bold uppercase text-amber-800 tracking-wider">
            25% Constitutional Threshold
          </span>
          <div className="text-2xl font-black text-amber-800 mt-1">
            {stats.statesMeeting25Percent} <span className="text-xs font-normal text-amber-700">/ 24 Req.</span>
          </div>
          <p className="text-[11px] text-amber-800 font-bold mt-1">
            {stats.statesMeeting25Percent >= 24 ? '✓ Met Constitutional Requirement' : '24 States Required'}
          </p>
        </div>

        <div className="bg-white border border-slate-200 p-4 rounded-2xl shadow-xs">
          <span className="text-[10px] font-bold uppercase text-slate-500 tracking-wider">
            National Lead Margin
          </span>
          <div className="text-2xl font-black text-emerald-800 mt-1">
            {stats.hasAnyVotes ? (stats.nationalLeadMargin >= 0 ? `+${stats.nationalLeadMargin.toLocaleString()}` : stats.nationalLeadMargin.toLocaleString()) : '0'}
          </div>
          <p className="text-[11px] text-slate-600 font-medium mt-1">
            {stats.hasAnyVotes ? 'Over APC Candidate' : 'Even Baseline'}
          </p>
        </div>
      </div>

      {/* Filter and Search Bar */}
      <div className="bg-white border border-slate-200 p-4 rounded-2xl shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-3">
        {/* Search Input */}
        <div className="relative flex-1 max-w-md">
          <Search className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search state name or state code (e.g. Lagos, 24, Kano)..."
            className="w-full bg-slate-50 border border-slate-300 text-slate-900 text-xs rounded-xl pl-9 pr-4 py-2.5 focus:outline-none focus:border-emerald-600 focus:bg-white font-medium"
          />
        </div>

        {/* Zone & Sort Filter */}
        <div className="flex flex-wrap items-center gap-2.5 text-xs">
          <div className="flex items-center space-x-1.5">
            <span className="text-slate-500 font-bold">Zone:</span>
            <select
              value={selectedZone}
              onChange={(e) => setSelectedZone(e.target.value)}
              className="bg-slate-50 border border-slate-300 text-slate-800 font-semibold px-3 py-2 rounded-xl focus:outline-none focus:border-emerald-600"
            >
              <option value="ALL">All 6 Geopolitical Zones</option>
              <option value="North West">North West (NW)</option>
              <option value="North East">North East (NE)</option>
              <option value="North Central">North Central (NC)</option>
              <option value="South West">South West (SW)</option>
              <option value="South East">South East (SE)</option>
              <option value="South South">South South (SS)</option>
            </select>
          </div>

          <div className="flex items-center space-x-1.5">
            <span className="text-slate-500 font-bold">Sort By:</span>
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as any)}
              className="bg-slate-50 border border-slate-300 text-slate-800 font-semibold px-3 py-2 rounded-xl focus:outline-none focus:border-emerald-600"
            >
              <option value="VOTES">Highest ADC Votes</option>
              <option value="MARGIN">Highest Vote Margin</option>
              <option value="TURNOUT">Registered Voters Size</option>
              <option value="NAME">Alphabetical (A-Z)</option>
            </select>
          </div>
        </div>
      </div>

      {/* State-by-State Data Table */}
      <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
        <div className="p-4 border-b border-slate-200 bg-slate-50 flex items-center justify-between">
          <span className="text-xs font-black uppercase tracking-wider text-slate-700">
            State-by-State Results &amp; Constitutional Threshold Breakdown
          </span>
          <span className="text-xs font-mono font-bold text-emerald-800">
            Showing {filteredStates.length} of 37 Jurisdictions
          </span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="bg-slate-100 text-slate-600 font-mono text-[10px] uppercase border-b border-slate-200">
              <tr>
                <th className="p-3">INEC Code</th>
                <th className="p-3">State</th>
                <th className="p-3">Zone</th>
                <th className="p-3 text-right">Reg. Voters</th>
                <th className="p-3 text-right">ADC (Atiku)</th>
                <th className="p-3 text-right">APC (Tinubu)</th>
                <th className="p-3 text-right">PDP</th>
                <th className="p-3 text-right">LP (Obi)</th>
                <th className="p-3 text-right">ADC Share</th>
                <th className="p-3 text-center">25% Threshold</th>
                <th className="p-3 text-center">State Winner</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200 font-mono">
              {filteredStates.map((s) => {
                const adc = s.votes?.ADC || 0;
                const apc = s.votes?.APC || 0;
                const pdp = s.votes?.PDP || 0;
                const lp = s.votes?.LP || 0;
                const total = adc + apc + pdp + lp;
                const pct = total > 0 ? (adc / total) * 100 : 0;
                const passes25 = pct >= 25;
                const isWinner = adc > apc;

                return (
                  <tr key={s.id} className="hover:bg-emerald-50/50 transition">
                    <td className="p-3 font-bold text-slate-500">
                      <span className="px-2 py-0.5 rounded bg-slate-100 text-slate-800 font-mono font-bold text-[11px] border border-slate-300">
                        [{s.id}]
                      </span>
                    </td>
                    <td className="p-3 font-bold text-slate-900 font-sans text-sm">
                      {s.name}
                    </td>
                    <td className="p-3 text-slate-600 font-sans">{s.geopolitical_zone}</td>
                    <td className="p-3 text-right font-semibold text-slate-700">
                      {s.registered_voters.toLocaleString()}
                    </td>
                    <td className="p-3 text-right font-black text-emerald-800 text-sm">
                      {adc.toLocaleString()}
                    </td>
                    <td className="p-3 text-right text-slate-600">{apc.toLocaleString()}</td>
                    <td className="p-3 text-right text-slate-500">{pdp.toLocaleString()}</td>
                    <td className="p-3 text-right text-slate-500">{lp.toLocaleString()}</td>
                    <td className="p-3 text-right font-bold text-emerald-800">
                      {pct.toFixed(1)}%
                    </td>
                    <td className="p-3 text-center font-sans">
                      {total === 0 ? (
                        <span className="inline-flex items-center px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 text-[10px] font-medium border border-slate-200">
                          Pending
                        </span>
                      ) : passes25 ? (
                        <span className="inline-flex items-center space-x-1 px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-800 text-[10px] font-bold border border-emerald-300">
                          <CheckCircle2 className="w-3 h-3 text-emerald-700" />
                          <span>Met 25%</span>
                        </span>
                      ) : (
                        <span className="inline-flex items-center space-x-1 px-2 py-0.5 rounded-full bg-amber-100 text-amber-800 text-[10px] font-bold border border-amber-300">
                          <span>Below 25%</span>
                        </span>
                      )}
                    </td>
                    <td className="p-3 text-center font-sans">
                      {total === 0 ? (
                        <span className="text-slate-400 text-[10px] font-mono">-</span>
                      ) : isWinner ? (
                        <span className="px-2.5 py-1 rounded-lg bg-emerald-600 text-white font-bold text-[10px] shadow-xs">
                          ADC LEAD
                        </span>
                      ) : (
                        <span className="px-2.5 py-1 rounded-lg bg-slate-200 text-slate-700 font-bold text-[10px]">
                          APC
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
