'use client';

import React, { useState, useEffect } from 'react';
import { logout } from '@/lib/clientAuth';
import {
  FileSpreadsheet,
  Camera,
  CheckCircle2,
  AlertTriangle,
  UploadCloud,
  Check,
  ShieldAlert,
  ShieldCheck,
  Eye,
  LogOut,
  Sparkles,
  Lock,
  Vote
} from 'lucide-react';
import { POLITICAL_PARTIES } from '@/lib/electoralData';
import { saveModuleDraft, getModuleDraft } from '@/lib/offlineQueue';

interface Props {
  puCode: string;
  registeredVoters: number;
  onComplete: (data: any) => void;
  onSubmitToServer: (data: any) => Promise<boolean>;
}

export const ResultCollationModule: React.FC<Props> = ({
  puCode,
  registeredVoters,
  onComplete,
  onSubmitToServer,
}) => {
  const [logoutError, setLogoutError] = useState<string | null>(null);

  const [accreditedVoters, setAccreditedVoters] = useState<number>(465);
  const [rejectedBallots, setRejectedBallots] = useState<number>(5);

  // Party Votes (ADC Campaign Field Entry)
  const [partyVotes, setPartyVotes] = useState<Record<string, number>>({
    ADC: 245,
    APC: 155,
    LP: 53,
    PDP: 7,
    NNPP: 5,
    SDP: 0,
  });

  // Way 1: Form EC8A Image
  const [photoPreview, setPhotoPreview] = useState<string | null>(
    '/sample_ec8a_snap.jpg'
  );

  // Sworn Agent Signature
  const [agentSigned, setAgentSigned] = useState<boolean>(false);

  const [submitting, setSubmitting] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [submissionReceipt, setSubmissionReceipt] = useState<any>(null);

  // Math Auto-balance Calculations
  const totalValidVotes = Object.values(partyVotes).reduce((sum, v) => sum + (Number(v) || 0), 0);
  const totalVotesCast = totalValidVotes + (Number(rejectedBallots) || 0);
  const isBalanced = totalVotesCast === Number(accreditedVoters);
  const discrepancy = Math.abs(totalVotesCast - Number(accreditedVoters));

  // ANTI-OVER-VOTING CHECK (Section 51 Electoral Act 2022)
  const isOverVoting = totalVotesCast > Number(accreditedVoters);
  const isOverAccredited = Number(accreditedVoters) > Number(registeredVoters);

  // Load draft
  useEffect(() => {
    const draft = getModuleDraft<any>(puCode, 'result_collation');
    if (draft) {
      if (draft.accreditedVoters !== undefined) setAccreditedVoters(draft.accreditedVoters);
      if (draft.rejectedBallots !== undefined) setRejectedBallots(draft.rejectedBallots);
      if (draft.partyVotes) setPartyVotes(draft.partyVotes);
      if (draft.photoPreview) setPhotoPreview(draft.photoPreview);
      if (draft.agentSigned) setAgentSigned(draft.agentSigned);
    }
  }, [puCode]);

  const handlePartyVoteChange = (party: string, value: string) => {
    const num = Math.max(0, parseInt(value, 10) || 0);
    const updated = { ...partyVotes, [party]: num };
    setPartyVotes(updated);
    saveModuleDraft(puCode, 'result_collation', {
      accreditedVoters,
      rejectedBallots,
      partyVotes: updated,
      photoPreview,
      agentSigned,
    });
  };

  const handlePhotoCapture = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const base64 = event.target?.result as string;
        setPhotoPreview(base64);
        saveModuleDraft(puCode, 'result_collation', {
          accreditedVoters,
          rejectedBallots,
          partyVotes,
          photoPreview: base64,
          agentSigned,
        });
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!agentSigned) {
      alert('Please check the Sworn Agent Sign-off box to affirm and certify these results.');
      return;
    }

    setSubmitting(true);

    const payload = {
      pu_code: puCode,
      registered_voters: registeredVoters,
      accredited_voters: accreditedVoters,
      rejected_ballots: rejectedBallots,
      party_votes: partyVotes,
      total_valid_votes: totalValidVotes,
      total_votes_cast: totalVotesCast,
      form_ec8a_url: photoPreview || '/sample_ec8a_snap.jpg',
      is_balanced: isBalanced,
      discrepancy_count: discrepancy,
      over_voting_detected: isOverVoting,
      agent_signature_confirmed: agentSigned,
      agent_signed_at: new Date().toISOString(),
      timestamp: new Date().toISOString(),
    };

    const success = await onSubmitToServer(payload);
    setSubmitting(false);

    if (success) {
      setSubmitSuccess(true);
      setSubmissionReceipt(payload);
      onComplete(payload);
    }
  };

  const handleLogout = async () => {
    setLogoutError(null);
    try {
      await logout();
    } catch (error: unknown) {
      setLogoutError(error instanceof Error ? error.message : 'Unable to sign out. Please try again.');
    }
  };

  // IF SUBMITTED: Render the official post-submission confirmation & logout screen
  if (submitSuccess) {
    return (
      <div className="bg-slate-900 border-2 border-emerald-500/80 rounded-2xl p-6 shadow-2xl animate-in zoom-in-95">
        {logoutError && <div role="alert" className="mb-3 text-rose-400">{logoutError}</div>}
        <div className="text-center space-y-4">
          <div className="w-16 h-16 rounded-full bg-emerald-950 border-2 border-emerald-500 flex items-center justify-center mx-auto shadow-lg shadow-emerald-950">
            <CheckCircle2 className="w-10 h-10 text-emerald-400" />
          </div>

          <div>
            <span className="text-xs uppercase font-bold tracking-widest text-emerald-400 bg-emerald-950/80 px-3 py-1 rounded-full border border-emerald-700">
              TRANSMISSION RECORD CONFIRMED
            </span>
            <h2 className="text-xl font-black text-white mt-2">
              SUBMITTED & TRANSMITTED TO ADC CAMPAIGN HQ
            </h2>
            <p className="text-xs text-slate-300 max-w-md mx-auto mt-1">
              Your sworn Form EC8A declaration and e-EC8A returns for Polling Unit{' '}
              <strong className="text-amber-300 font-mono">{puCode}</strong> have been cryptographically sealed and synced into the national tabulation database.
            </p>
          </div>

          {/* Collation Summary Receipt */}
          <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 text-left space-y-2.5 text-xs font-mono">
            <div className="flex justify-between border-b border-slate-800 pb-2">
              <span className="text-slate-400">PU Delimitation Code:</span>
              <span className="text-white font-bold">{puCode}</span>
            </div>
            <div className="flex justify-between border-b border-slate-800 pb-2">
              <span className="text-slate-400">Accredited Voters (BVAS):</span>
              <span className="text-emerald-400 font-bold">{accreditedVoters}</span>
            </div>
            <div className="flex justify-between border-b border-slate-800 pb-2">
              <span className="text-slate-400">Total Valid Votes:</span>
              <span className="text-white font-bold">{totalValidVotes}</span>
            </div>
            <div className="flex justify-between border-b border-slate-800 pb-2">
              <span className="text-slate-400">ADC Candidate Votes:</span>
              <span className="text-purple-400 font-extrabold text-sm">{partyVotes.ADC || 0} votes</span>
            </div>
            <div className="flex justify-between border-b border-slate-800 pb-2">
              <span className="text-slate-400">Section 51 Over-Voting Status:</span>
              <span className={isOverVoting ? 'text-rose-400 font-bold' : 'text-emerald-400 font-bold'}>
                {isOverVoting ? 'VIOLATION DETECTED' : 'CLEAN & BALANCED'}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-400">Transmission Timestamp:</span>
              <span className="text-slate-300">{new Date().toLocaleTimeString()} &bull; 27 Feb 2027</span>
            </div>
          </div>

          {/* Form EC8A Attached Snapshot Confirmation */}
          {photoPreview && (
            <div className="p-3 bg-slate-950 rounded-xl border border-slate-800 flex items-center justify-between">
              <div className="flex items-center gap-2 text-xs text-slate-300">
                <Camera className="w-4 h-4 text-emerald-400" />
                <span>Signed Physical Form EC8A Snapshot Cloud-Archived</span>
              </div>
              <a
                href={photoPreview}
                target="_blank"
                rel="noreferrer"
                className="text-[11px] text-purple-400 hover:underline flex items-center gap-1 font-bold"
              >
                <Eye className="w-3.5 h-3.5" /> View Upload
              </a>
            </div>
          )}

          {/* Safe Sign-Out Button */}
          <div className="pt-2">
            <button
              type="button"
              onClick={handleLogout}
              className="w-full py-3.5 px-4 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold text-sm shadow-xl shadow-purple-950/80 flex items-center justify-center gap-2 transition group"
            >
              <LogOut className="w-4 h-4 group-hover:-translate-x-1 transition" />
              <span>Sign Out & Close Shift (PU Agent Duty Complete)</span>
            </button>
            <p className="text-[11px] text-slate-500 mt-2">
              Thank you for safeguarding the votes of the African Democratic Congress (ADC).
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-xl">
      <div className="flex items-center justify-between pb-3 border-b border-slate-800">
        <div className="flex items-center space-x-2.5">
          <div className="w-8 h-8 rounded-lg bg-slate-800 border border-amber-500/40 text-amber-400 flex items-center justify-center font-bold text-sm">
            5
          </div>
          <div>
            <h3 className="text-sm font-bold text-white">Result Sheet Submission (Two-Way Collation)</h3>
            <p className="text-[11px] text-slate-400">
              Way 1: Form EC8A camera snapshot &bull; Way 2: e-EC8A anti-over-voting calculator
            </p>
          </div>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="mt-4 space-y-5">
        {/* CRITICAL: SECTION 51 OVER-VOTING ALERT BANNER */}
        {isOverVoting && (
          <div className="p-4 rounded-xl bg-red-950/90 border-2 border-red-600 text-red-100 animate-pulse shadow-lg">
            <div className="flex items-start space-x-3">
              <ShieldAlert className="w-6 h-6 text-red-400 flex-shrink-0 mt-0.5" />
              <div>
                <h4 className="text-xs font-black uppercase tracking-wider text-red-200 flex items-center gap-2">
                  <span>SECTION 51 ELECTORAL ACT 2022 OVER-VOTING VIOLATION!</span>
                </h4>
                <p className="text-xs mt-1 text-red-200">
                  Total Votes Cast (<strong className="text-white">{totalVotesCast}</strong>) exceeds BVAS Accredited Voters (<strong className="text-white">{accreditedVoters}</strong>) by{' '}
                  <strong className="text-white font-mono">+{totalVotesCast - accreditedVoters} votes</strong>!
                </p>
                <p className="text-[11px] text-red-300 mt-1">
                  Under Section 51(2) of the Electoral Act 2022, the election in this Polling Unit will be declared void by INEC if not reconciled before transmission.
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Top Delimitation & Accreditation Bar */}
        <div className="grid grid-cols-3 gap-2 p-3 bg-slate-950 rounded-xl border border-slate-800 text-center">
          <div>
            <span className="block text-[10px] text-slate-400 uppercase font-semibold flex items-center justify-center gap-1">
              Registered Voters
              <Lock className="w-2.5 h-2.5 text-amber-400" />
            </span>
            <span className="text-sm font-mono font-bold text-white">{registeredVoters.toLocaleString()}</span>
            <span className="block text-[9px] text-amber-300 font-medium">Statutory Baseline</span>
          </div>
          <div>
            <span className="block text-[10px] text-slate-400 uppercase font-semibold">Accredited (BVAS)</span>
            <input
              type="number"
              min={0}
              max={registeredVoters}
              value={accreditedVoters}
              onChange={(e) => setAccreditedVoters(Math.max(0, Number(e.target.value)))}
              className={`w-full mt-0.5 text-center text-sm font-mono font-bold bg-slate-900 border rounded-md py-0.5 focus:outline-none ${
                isOverAccredited
                  ? 'text-rose-400 border-rose-500 animate-pulse'
                  : 'text-emerald-400 border-slate-700 focus:border-purple-500'
              }`}
            />
            {isOverAccredited && (
              <span className="block text-[9px] text-rose-400 font-bold">Exceeds Register!</span>
            )}
          </div>
          <div>
            <span className="block text-[10px] text-slate-400 uppercase font-semibold">Rejected Ballots</span>
            <input
              type="number"
              min={0}
              value={rejectedBallots}
              onChange={(e) => setRejectedBallots(Math.max(0, Number(e.target.value)))}
              className="w-full mt-0.5 text-center text-sm font-mono font-bold text-rose-400 bg-slate-900 border border-slate-700 rounded-md py-0.5 focus:outline-none focus:border-rose-500"
            />
          </div>
        </div>

        {/* Dynamic Auto-Balance Validation Badge */}
        <div
          className={`p-3 rounded-xl border flex items-center justify-between transition-all ${
            isBalanced
              ? 'bg-emerald-950/40 border-emerald-500/80 text-emerald-200'
              : 'bg-rose-950/50 border-rose-500/80 text-rose-200'
          }`}
        >
          <div className="flex items-center space-x-2">
            {isBalanced ? (
              <CheckCircle2 className="w-5 h-5 text-emerald-400 flex-shrink-0" />
            ) : (
              <ShieldAlert className="w-5 h-5 text-rose-400 flex-shrink-0" />
            )}
            <div>
              <div className="text-xs font-bold flex items-center gap-1.5">
                {isBalanced ? 'MATHEMATICALLY BALANCED (ZERO OVER-VOTING)' : 'MATHEMATICAL DISCREPANCY DETECTED'}
              </div>
              <div className="text-[11px] opacity-90">
                Valid ({totalValidVotes}) + Rejected ({rejectedBallots}) = <strong>{totalVotesCast}</strong> vs Accredited ({accreditedVoters})
              </div>
            </div>
          </div>

          <div className="text-right">
            <span
              className={`text-xs font-mono font-extrabold px-2 py-1 rounded ${
                isBalanced
                  ? 'bg-emerald-800/80 text-emerald-100'
                  : 'bg-rose-800/90 text-rose-100'
              }`}
            >
              {isBalanced ? 'Delta: 0' : `Delta: ${totalVotesCast > accreditedVoters ? '+' : ''}${totalVotesCast - accreditedVoters}`}
            </span>
          </div>
        </div>

        {/* WAY 1: Camera Snapshot of Physical Signed Form EC8A */}
        <div className="p-4 bg-slate-950 rounded-xl border border-purple-900/40">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs font-bold text-purple-300 uppercase tracking-wider flex items-center gap-1.5">
              <Camera className="w-4 h-4 text-amber-400" />
              Way 1: Snap Physical Signed Form EC8A
            </span>
            <span className="text-[10px] text-amber-400 font-semibold bg-purple-950 px-2 py-0.5 rounded border border-purple-800">
              Required for Court Evidence
            </span>
          </div>

          <div className="flex flex-col sm:flex-row items-center gap-4">
            {photoPreview ? (
              <div className="relative w-full sm:w-44 h-32 rounded-xl overflow-hidden border border-purple-500/60 bg-slate-900 group shadow-md">
                <img
                  src={photoPreview}
                  alt="Form EC8A Preview"
                  className="w-full h-full object-cover"
                />
                <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition flex items-center justify-center gap-2">
                  <a
                    href={photoPreview}
                    target="_blank"
                    rel="noreferrer"
                    className="p-1.5 bg-slate-800 rounded-full text-white hover:bg-slate-700"
                  >
                    <Eye className="w-4 h-4" />
                  </a>
                </div>
                <span className="absolute bottom-1 right-1 bg-purple-950/90 text-amber-300 text-[9px] px-1.5 py-0.5 rounded font-mono border border-purple-700">
                  Ready to Transmit
                </span>
              </div>
            ) : (
              <div className="w-full sm:w-44 h-32 rounded-xl border-2 border-dashed border-slate-700 flex flex-col items-center justify-center text-slate-500 text-xs">
                <UploadCloud className="w-6 h-6 mb-1 text-slate-400" />
                <span>No photo snapped</span>
              </div>
            )}

            <div className="flex-1 w-full space-y-2">
              <label className="flex items-center justify-center gap-2 w-full py-3 px-4 bg-purple-950/60 hover:bg-purple-900/60 text-white rounded-xl border border-purple-500 text-xs font-bold cursor-pointer transition shadow">
                <Camera className="w-4 h-4 text-amber-400" />
                <span>{photoPreview ? 'Re-Snap / Replace EC8A Photo' : 'Snap Form EC8A with Camera'}</span>
                <input
                  type="file"
                  accept="image/*"
                  capture="environment"
                  onChange={handlePhotoCapture}
                  className="hidden"
                />
              </label>
              <p className="text-[10px] text-slate-400 text-center sm:text-left">
                Ensure all INEC Presiding Officer signatures and party agent counters are clearly readable. Image is locally cached offline if network is unstable.
              </p>
            </div>
          </div>
        </div>

        {/* WAY 2: e-EC8A Filling Section with Anti-Over-Voting Calculation */}
        <div className="p-4 bg-slate-950 rounded-xl border border-purple-900/40 space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold text-purple-300 uppercase tracking-wider flex items-center gap-1.5">
              <FileSpreadsheet className="w-4 h-4 text-amber-400" />
              Way 2: e-EC8A Filling Section (Party Votes)
            </span>
            <span className="text-[10px] text-slate-400 font-mono">
              Total Valid: <strong className="text-white">{totalValidVotes}</strong>
            </span>
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-3 gap-2.5">
            {POLITICAL_PARTIES.map((party) => {
              const isAdc = party.code === 'ADC';
              return (
                <div
                  key={party.code}
                  className={`p-2.5 rounded-xl border flex items-center justify-between space-x-2 transition ${
                    isAdc
                      ? 'bg-slate-800/90 border-amber-500/80 shadow-md ring-1 ring-amber-500/40'
                      : 'bg-slate-900 border-slate-800'
                  }`}
                >
                  <div className="flex items-center space-x-2">
                    <span
                      className="w-3 h-3 rounded-full shrink-0"
                      style={{ backgroundColor: party.color }}
                    />
                    <div>
                      <span className={`text-xs font-black block ${isAdc ? 'text-amber-400' : 'text-white'}`}>
                        {party.code}
                      </span>
                      <span className="text-[9px] text-slate-400 line-clamp-1">{party.name}</span>
                    </div>
                  </div>
                  <input
                    type="number"
                    min={0}
                    value={partyVotes[party.code] ?? 0}
                    onChange={(e) => handlePartyVoteChange(party.code, e.target.value)}
                    className={`w-16 py-1 px-1.5 bg-slate-950 border rounded-lg text-right text-xs font-mono font-bold text-white focus:outline-none ${
                      isAdc ? 'border-amber-400 text-amber-300' : 'border-slate-700 focus:border-amber-500'
                    }`}
                  />
                </div>
              );
            })}
          </div>
        </div>

        {/* SWORN AGENT SIGN-OFF AFFIDAVIT CHECKBOX */}
        <div className="p-4 rounded-xl bg-slate-950 border border-amber-500/40 space-y-2">
          <label className="flex items-start gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={agentSigned}
              onChange={(e) => setAgentSigned(e.target.checked)}
              className="mt-1 w-4 h-4 accent-amber-500 rounded cursor-pointer"
            />
            <div className="text-xs text-slate-200 leading-relaxed">
              <strong className="text-amber-400 block mb-0.5">
                Sworn Agent Declaration & Electronic Signature
              </strong>
              I, accredited ADC Polling Unit Agent for PU <span className="font-mono text-white">{puCode}</span>, affirm that these figures and the Form EC8A photograph represent the true, uncorrupted declaration of polls at this Polling Station.
            </div>
          </label>
        </div>

        {/* Transmit Button */}
        <button
          type="submit"
          disabled={submitting || !agentSigned}
          className={`w-full py-3.5 px-4 rounded-xl font-bold text-xs uppercase tracking-wider flex items-center justify-center gap-2 shadow-lg transition ${
            !agentSigned
              ? 'bg-slate-800 text-slate-500 cursor-not-allowed border border-slate-700'
              : isOverVoting
              ? 'bg-red-700 hover:bg-red-600 text-white shadow-red-950'
              : 'bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-md'
          } disabled:opacity-50`}
        >
          {submitting ? (
            'Transmitting Collation Package...'
          ) : !agentSigned ? (
            <>
              <Lock className="w-4 h-4" /> Check Sign-off Box to Submit
            </>
          ) : isOverVoting ? (
            <>
              <AlertTriangle className="w-4 h-4" /> Transmit Over-Voting Alert to HQ
            </>
          ) : (
            <>
              <Check className="w-4 h-4 text-slate-950" /> Sign & Transmit EC8A to Situation Room
            </>
          )}
        </button>
      </form>
    </div>
  );
};
