'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Camera, CheckCircle2, FileText, ShieldCheck, AlertOctagon, X, RotateCw, Video, Image as ImageIcon, Sparkles, AlertTriangle, Lock } from 'lucide-react';
import { ALL_18_POLITICAL_PARTIES, getStatutoryRegisteredVotersForPu } from '@/lib/electoralData';

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

export const Step6ResultsData: React.FC<Props> = ({ puCode, registeredVoters, onSubmit, onNext }) => {
  const registeredTotal = registeredVoters || getStatutoryRegisteredVotersForPu(puCode);
  // Initialize votes state for all 18 official INEC parties
  const [votes, setVotes] = useState<Record<string, number>>(() => {
    const initial: Record<string, number> = {};
    ALL_18_POLITICAL_PARTIES.forEach((p) => {
      if (p.code === 'ADC') initial[p.code] = 145;
      else if (p.code === 'APC') initial[p.code] = 68;
      else if (p.code === 'PDP') initial[p.code] = 32;
      else if (p.code === 'LP') initial[p.code] = 14;
      else if (p.code === 'NNPP') initial[p.code] = 6;
      else if (p.code === 'SDP') initial[p.code] = 2;
      else initial[p.code] = 0;
    });
    return initial;
  });

  const [physicalEc8aPhoto, setPhysicalEc8aPhoto] = useState<string | null>(
    '/sample_ec8a_snap.jpg'
  );

  // Legibility Quality Status ('READABLE' | 'UNREADABLE' | 'SCANNING' | null)
  const [legibilityStatus, setLegibilityStatus] = useState<'READABLE' | 'UNREADABLE' | 'SCANNING'>('READABLE');
  const [legibilityScore, setLegibilityScore] = useState<number>(98.6);

  const [isCameraActive, setIsCameraActive] = useState<boolean>(false);
  const [cameraError, setCameraError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  const videoRef = useRef<HTMLVideoElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const streamRef = useRef<MediaStream | null>(null);

  const totalVotesCast = Object.values(votes).reduce((a, b) => a + b, 0);

  const handleVoteChange = (partyCode: string, val: number) => {
    setVotes((prev) => ({
      ...prev,
      [partyCode]: Math.max(0, val),
    }));
  };

  // Start Live Device Camera Stream
  const startCamera = async () => {
    setCameraError(null);
    setIsCameraActive(true);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: { ideal: 'environment' }, width: { ideal: 1920 }, height: { ideal: 1080 } },
        audio: false,
      });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        videoRef.current.play();
      }
    } catch (err: any) {
      console.warn('Camera stream error:', err);
      setCameraError('Direct camera stream unavailable. Please use local gallery file uploader.');
    }
  };

  const stopCamera = () => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach((t) => t.stop());
      streamRef.current = null;
    }
    setIsCameraActive(false);
  };

  // Run AI Quality & Legibility Scan
  const runLegibilityScan = (imageSrc: string) => {
    setPhysicalEc8aPhoto(imageSrc);
    setLegibilityStatus('SCANNING');

    setTimeout(() => {
      // Simulate clarity test (98.6% readable)
      setLegibilityStatus('READABLE');
      setLegibilityScore(98.6);
    }, 1500);
  };

  // Capture Photo from Video Canvas
  const captureSnapshot = () => {
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      canvas.width = video.videoWidth || 1280;
      canvas.height = video.videoHeight || 720;
      const ctx = canvas.getContext('2d');
      if (ctx) {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const dataUrl = canvas.toDataURL('image/jpeg', 0.95);
        stopCamera();
        runLegibilityScan(dataUrl);
      }
    } else {
      stopCamera();
      runLegibilityScan(`/sample_ec8a_snap.jpg&t=${Date.now()}`);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          stopCamera();
          runLegibilityScan(event.target.result as string);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  // Force Unreadable Test Simulation (For user testing)
  const simulateUnreadablePhoto = () => {
    setLegibilityStatus('UNREADABLE');
    setLegibilityScore(32.4);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (legibilityStatus === 'UNREADABLE') {
      alert('Form EC8A photo is unreadable/blurry! Please retake a clear photo under proper lighting before submitting.');
      return;
    }

    setSubmitting(true);
    const payload = {
      pu_code: puCode,
      registered_voters: registeredTotal,
      party_votes: votes,
      votes,
      accredited_voters: totalVotesCast,
      total_valid_votes: totalVotesCast,
      total_votes_cast: totalVotesCast,
      rejected_ballots: 0,
      form_ec8a_url: physicalEc8aPhoto || '/sample_ec8a_snap.jpg',
      physical_ec8a_photo: physicalEc8aPhoto || '/sample_ec8a_snap.jpg',
      legibility_status: legibilityStatus,
      legibility_score: legibilityScore,
      timestamp: new Date().toISOString(),
    };

    const success = await onSubmit(payload);
    setSubmitting(false);
    if (success) {
      setIsSubmitted(true);
      onNext();
    }
  };

  useEffect(() => {
    return () => {
      stopCamera();
    };
  }, []);

  return (
    <div className="bg-white text-slate-900 border border-emerald-900/20 rounded-2xl p-5 shadow-xl font-sans">
      <input
        type="file"
        ref={fileInputRef}
        accept="image/*"
        capture="environment"
        onChange={handleFileChange}
        className="hidden"
      />
      <canvas ref={canvasRef} className="hidden" />

      {/* Header */}
      <div className="border-b border-emerald-100 pb-3 mb-4">
        <span className="text-[10px] font-bold text-emerald-800 bg-emerald-100 px-2 py-0.5 rounded-full uppercase tracking-wider">
          6. Result Upload &amp; e-EC8A (6:00 PM - 10:30 PM)
        </span>
        <h2 className="text-lg font-black text-emerald-950 mt-1">Official INEC Form EC8A Entry</h2>
        <p className="text-xs text-slate-500">Record votes for all 18 registered political parties &amp; upload certified EC8A photo.</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-5">
        {/* Form EC8A Photo & AI Legibility Check Card */}
        <div className="bg-slate-900 text-white p-4 rounded-2xl border border-emerald-500/40 shadow-xl space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-xs font-black text-emerald-400 uppercase tracking-wider flex items-center gap-1.5">
              <Camera className="w-4 h-4 text-emerald-400" /> Form EC8A Certified Photo Snap
            </span>
            <span className="text-[10px] font-mono bg-slate-800 text-slate-300 px-2 py-0.5 rounded">
              Electoral Act Sec 60(5)
            </span>
          </div>

          {/* Photo Viewport Display */}
          <div className="relative rounded-xl overflow-hidden border border-slate-700 bg-black h-48 flex items-center justify-center">
            {physicalEc8aPhoto ? (
              <img src={physicalEc8aPhoto} alt="Physical EC8A Result Sheet" className="w-full h-full object-cover" />
            ) : (
              <div className="text-center p-4 text-slate-500">
                <Camera className="w-8 h-8 mx-auto mb-1" />
                <span className="text-xs">Tap camera button to snap EC8A sheet</span>
              </div>
            )}

            {/* AI Scanning HUD Overlay */}
            {legibilityStatus === 'SCANNING' && (
              <div className="absolute inset-0 bg-emerald-950/80 backdrop-blur-xs flex flex-col items-center justify-center">
                <div className="w-full h-1 bg-emerald-400 shadow-[0_0_15px_#10b981] animate-bounce" />
                <p className="text-xs font-mono font-bold text-emerald-300 mt-3 animate-pulse">
                  VERIFYING TEXT SHARPNESS &amp; LEGIBILITY...
                </p>
              </div>
            )}

            <div className="absolute bottom-2 right-2 flex items-center gap-2">
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="px-2.5 py-1.5 bg-slate-900/90 hover:bg-slate-800 text-white text-[10px] font-bold rounded-lg shadow border border-slate-700 flex items-center gap-1"
              >
                <ImageIcon className="w-3.5 h-3.5 text-slate-400" />
                <span>Gallery</span>
              </button>
              <button
                type="button"
                onClick={startCamera}
                className="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-[10px] font-black rounded-lg shadow flex items-center gap-1.5"
              >
                <Camera className="w-3.5 h-3.5" />
                <span>📸 Snap EC8A Sheet</span>
              </button>
            </div>
          </div>

          {/* AI Legibility Status Banner */}
          {legibilityStatus === 'READABLE' && (
            <div className="bg-emerald-950/80 border border-emerald-500/50 rounded-xl p-3 flex items-center justify-between text-emerald-200 text-xs">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0" />
                <div>
                  <span className="font-extrabold text-white block">✅ Form EC8A Certified Legible</span>
                  <span className="text-[10px] text-emerald-300">Text sharpness &amp; figures certified 100% readable</span>
                </div>
              </div>
              <span className="font-mono font-black text-emerald-300 text-xs bg-emerald-900/90 px-2 py-0.5 rounded border border-emerald-500/40">
                {legibilityScore}% Score
              </span>
            </div>
          )}

          {legibilityStatus === 'UNREADABLE' && (
            <div className="bg-rose-950/90 border border-rose-500/60 rounded-xl p-3 space-y-2 text-rose-200 text-xs">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <AlertOctagon className="w-4.5 h-4.5 text-rose-400 shrink-0 animate-pulse" />
                  <span className="font-extrabold text-white">⚠️ PHOTO UNREADABLE / BLURRY</span>
                </div>
                <span className="font-mono font-black text-rose-300 text-xs bg-rose-900/90 px-2 py-0.5 rounded border border-rose-500/40">
                  {legibilityScore}% Low Score
                </span>
              </div>
              <p className="text-[11px] text-rose-200 leading-relaxed bg-rose-900/40 p-2 rounded-lg border border-rose-800">
                Camera scan detected blur or glare. Per INEC guidelines, unreadable EC8A forms CANNOT be submitted. Please resnap under clear lighting.
              </p>
              <button
                type="button"
                onClick={startCamera}
                className="w-full py-2 bg-rose-600 hover:bg-rose-500 text-white font-black text-xs rounded-lg shadow"
              >
                📸 Resnap EC8A Sheet Now
              </button>
            </div>
          )}

          {/* Quick Mock Toggle Button for Testing */}
          <div className="flex justify-end pt-1">
            <button
              type="button"
              onClick={simulateUnreadablePhoto}
              className="text-[10px] text-slate-400 hover:text-amber-300 underline font-mono"
            >
              Test Unreadable Blurry Photo Error
            </button>
          </div>
        </div>

        {/* 18 Official INEC Parties Results Entry Table */}
        <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200 space-y-3">
          <div className="flex items-center justify-between border-b border-slate-200 pb-2">
            <div>
              <span className="text-xs font-black text-slate-900 uppercase tracking-wider block">
                All 18 INEC Participating Political Parties
              </span>
              <span className="text-[10px] text-slate-500 font-medium">
                Official Ballot Results Entry for PU {puCode}
              </span>
              <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-800 bg-emerald-100/90 px-2 py-0.5 rounded-full border border-emerald-300 mt-0.5">
                <Lock className="w-2.5 h-2.5" /> Statutory Baseline: {registeredTotal.toLocaleString()} Voters (Unchangeable)
              </span>
            </div>
            <div className="text-right">
              <span className="text-xs font-black text-emerald-800 font-mono block">
                {totalVotesCast.toLocaleString()} / {registeredTotal.toLocaleString()}
              </span>
              <span className="text-[9px] text-slate-500 font-bold uppercase">
                Turnout: {registeredTotal > 0 ? ((totalVotesCast / registeredTotal) * 100).toFixed(1) : 0}%
              </span>
            </div>
          </div>

          {/* 18 Parties Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-[380px] overflow-y-auto pr-1">
            {ALL_18_POLITICAL_PARTIES.map((party) => {
              const count = votes[party.code] || 0;

              return (
                <div
                  key={party.code}
                  className={`flex items-center justify-between p-2.5 rounded-xl border transition-all ${
                    party.isMain
                      ? 'bg-purple-50/90 border-purple-400 shadow-sm ring-1 ring-purple-300'
                      : 'bg-white border-slate-200 hover:border-slate-300'
                  }`}
                >
                  <div className="flex items-center space-x-2.5 truncate">
                    <span
                      className="w-3.5 h-3.5 rounded-full inline-block shrink-0 shadow-sm"
                      style={{ backgroundColor: party.color }}
                    />
                    <div className="truncate">
                      <span className="text-xs font-black text-slate-900">{party.code}</span>
                      <span className="text-[10px] text-slate-500 block truncate max-w-[140px]">
                        {party.name}
                      </span>
                    </div>
                  </div>

                  <input
                    type="number"
                    min="0"
                    value={count}
                    onChange={(e) => handleVoteChange(party.code, Number(e.target.value))}
                    className="w-20 px-2.5 py-1 text-right font-mono font-black text-sm border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-600 bg-slate-50"
                  />
                </div>
              );
            })}
          </div>
        </div>

        {/* Primary Action Button */}
        <button
          type="submit"
          disabled={submitting || legibilityStatus === 'UNREADABLE'}
          className={`w-full py-3.5 px-4 rounded-xl font-black text-sm shadow-md transition active:scale-98 flex items-center justify-center gap-2 ${
            legibilityStatus === 'UNREADABLE'
              ? 'bg-slate-400 text-slate-200 cursor-not-allowed'
              : 'bg-[#065F46] hover:bg-[#047857] text-white'
          }`}
        >
          {submitting ? (
            <span>Uploading Form EC8A Payload...</span>
          ) : (
            <>
              {isSubmitted && <CheckCircle2 className="w-4 h-4 text-emerald-300" />}
              <span>Submit Form EC8A &amp; Finalize Polling Unit Result</span>
            </>
          )}
        </button>

        {legibilityStatus === 'UNREADABLE' && (
          <p className="text-[11px] text-center text-rose-600 font-bold">
            ⚠️ Submission locked until Form EC8A photo is clear and readable.
          </p>
        )}
      </form>

      {/* Live Camera Stream Modal for EC8A */}
      {isCameraActive && (
        <div className="fixed inset-0 z-50 bg-slate-950/90 flex flex-col items-center justify-center p-4">
          <div className="bg-slate-900 border border-emerald-500/40 rounded-2xl p-4 w-full max-w-lg shadow-2xl">
            <div className="flex items-center justify-between mb-3 text-white">
              <h3 className="text-sm font-bold flex items-center gap-2">
                <Video className="w-4 h-4 text-emerald-400 animate-pulse" /> Live Form EC8A Camera Stream
              </h3>
              <button
                type="button"
                onClick={stopCamera}
                className="p-1 text-slate-400 hover:text-white rounded-lg"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {cameraError ? (
              <div className="p-4 bg-rose-950/60 border border-rose-500/40 rounded-xl text-rose-200 text-xs mb-3">
                {cameraError}
              </div>
            ) : (
              <div className="relative rounded-xl overflow-hidden bg-black aspect-video border border-slate-700">
                <video ref={videoRef} className="w-full h-full object-cover" playsInline muted />
                <div className="absolute inset-0 border-2 border-emerald-500/50 pointer-events-none rounded-xl" />
                <div className="absolute top-2 left-2 bg-emerald-950/80 text-emerald-300 text-[10px] px-2 py-0.5 rounded font-mono">
                  LIVE EC8A STREAM ACTIVE
                </div>
              </div>
            )}

            <div className="mt-4 flex items-center justify-between gap-3">
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="px-3 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold rounded-xl flex items-center gap-1.5"
              >
                <ImageIcon className="w-4 h-4 text-slate-400" />
                <span>Upload File</span>
              </button>

              <button
                type="button"
                onClick={captureSnapshot}
                className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-black text-xs rounded-xl shadow-lg flex items-center gap-2"
              >
                <Camera className="w-4 h-4" />
                <span>📸 Snap EC8A Form</span>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
