'use client';

import React, { useState, useEffect } from 'react';
import {
  Activity,
  Plus,
  ShieldCheck,
  AlertTriangle,
  MessageSquare,
  Clock,
  ArrowRight,
  CheckCircle2
} from 'lucide-react';
import { OngoingTurnoutData } from '@/types';
import { saveModuleDraft, getModuleDraft } from '@/lib/offlineQueue';

interface Props {
  puCode: string;
  onComplete: (data: any) => void;
  onProceedToNext?: () => void;
}

export const ElectionOngoingModule: React.FC<Props> = ({ puCode, onComplete, onProceedToNext }) => {
  const [hourInterval, setHourInterval] = useState('11:00 AM');
  const [estimatedTurnout, setEstimatedTurnout] = useState<number>(180);
  const [isPeaceful, setIsPeaceful] = useState<boolean>(true);
  const [quickNote, setQuickNote] = useState('');
  const [timeline, setTimeline] = useState<OngoingTurnoutData[]>([
    {
      pu_id: puCode,
      hour_interval: '09:30 AM',
      estimated_voter_turnout: 85,
      is_peaceful: true,
      quick_note: 'Smooth accreditation, queues orderly.',
      timestamp: '09:30',
    },
  ]);
  const [hasLogged, setHasLogged] = useState<boolean>(true);

  useEffect(() => {
    const draft = getModuleDraft<OngoingTurnoutData[]>(puCode, 'ongoing_timeline');
    if (draft && draft.length > 0) {
      setTimeline(draft);
    }
  }, [puCode]);

  const handleAddLog = (e: React.FormEvent) => {
    e.preventDefault();
    const newEntry: OngoingTurnoutData = {
      pu_id: puCode,
      hour_interval: hourInterval,
      estimated_voter_turnout: estimatedTurnout,
      is_peaceful: isPeaceful,
      quick_note: quickNote,
      timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
    };

    const updated = [newEntry, ...timeline];
    setTimeline(updated);
    saveModuleDraft(puCode, 'ongoing_timeline', updated);
    setQuickNote('');
    setHasLogged(true);
    onComplete(updated);
  };

  const handleProceed = () => {
    onComplete(timeline);
    if (onProceedToNext) {
      onProceedToNext();
    }
  };

  return (
    <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-lg space-y-4">
      <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">
            3
          </div>
          <div>
            <h3 className="text-sm font-bold text-white">Election Ongoing & Hourly Turnout</h3>
            <p className="text-[11px] text-slate-400">Live turnout tracking and polling unit climate</p>
          </div>
        </div>
        <span className="text-[11px] font-mono text-slate-300 bg-slate-800 px-2 py-0.5 rounded border border-slate-700">
          {timeline.length} logs
        </span>
      </div>

      <form onSubmit={handleAddLog} className="space-y-3.5">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div>
            <label className="block text-[11px] font-medium text-slate-400 mb-1">Time Slot</label>
            <select
              value={hourInterval}
              onChange={(e) => setHourInterval(e.target.value)}
              className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs text-white focus:outline-none focus:border-amber-500"
            >
              <option value="10:00 AM">10:00 AM Interval</option>
              <option value="11:00 AM">11:00 AM Interval</option>
              <option value="12:00 PM">12:00 PM Interval</option>
              <option value="01:00 PM">01:00 PM Interval</option>
              <option value="02:00 PM">02:00 PM Interval</option>
            </select>
          </div>

          <div>
            <label className="block text-[11px] font-medium text-slate-400 mb-1">
              Estimated Voters Processed
            </label>
            <div className="flex items-center space-x-1">
              <button
                type="button"
                onClick={() => setEstimatedTurnout(Math.max(0, estimatedTurnout - 10))}
                className="w-9 h-9 rounded-lg bg-slate-800 hover:bg-slate-700 text-white font-bold text-base flex items-center justify-center shrink-0"
              >
                -
              </button>
              <input
                type="number"
                value={estimatedTurnout}
                onChange={(e) => setEstimatedTurnout(Number(e.target.value))}
                className="flex-1 py-2 px-2 bg-slate-950 border border-slate-800 rounded-lg text-center text-xs text-white font-mono font-bold focus:border-amber-500 focus:outline-none"
              />
              <button
                type="button"
                onClick={() => setEstimatedTurnout(estimatedTurnout + 10)}
                className="w-9 h-9 rounded-lg bg-slate-800 hover:bg-slate-700 text-white font-bold text-base flex items-center justify-center shrink-0"
              >
                +
              </button>
            </div>
          </div>
        </div>

        {/* Peaceful vs Disrupted Toggle */}
        <div>
          <label className="block text-xs font-semibold text-slate-300 mb-1.5">
            Unit Atmosphere Condition
          </label>
          <div className="grid grid-cols-2 gap-2">
            <button
              type="button"
              onClick={() => setIsPeaceful(true)}
              className={`py-2 px-3 rounded-xl border text-xs font-medium flex items-center justify-center gap-2 transition ${
                isPeaceful
                  ? 'bg-emerald-950/70 border-emerald-500 text-emerald-300'
                  : 'bg-slate-950 border-slate-800 text-slate-400'
              }`}
            >
              <ShieldCheck className="w-4 h-4 text-emerald-400" />
              Peaceful & Orderly
            </button>
            <button
              type="button"
              onClick={() => setIsPeaceful(false)}
              className={`py-2 px-3 rounded-xl border text-xs font-medium flex items-center justify-center gap-2 transition ${
                !isPeaceful
                  ? 'bg-amber-950/70 border-amber-500 text-amber-300'
                  : 'bg-slate-950 border-slate-800 text-slate-400'
              }`}
            >
              <AlertTriangle className="w-4 h-4 text-amber-400" />
              Tense / Disrupted
            </button>
          </div>
        </div>

        {/* Quick-Note Feed Input */}
        <div>
          <label className="block text-[11px] font-medium text-slate-400 mb-1">
            Quick Note / Update
          </label>
          <div className="flex gap-2">
            <input
              type="text"
              value={quickNote}
              onChange={(e) => setQuickNote(e.target.value)}
              placeholder="e.g. Turnout heavy, elderly given priority assistance"
              className="flex-1 py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs text-white placeholder-slate-600 focus:outline-none focus:border-amber-500"
            />
            <button
              type="submit"
              className="px-3.5 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-amber-400 border border-amber-500/40 font-semibold text-xs flex items-center gap-1 shrink-0 transition"
            >
              <Plus className="w-3.5 h-3.5" /> Log
            </button>
          </div>
        </div>
      </form>

      {/* Running Timeline Feed */}
      {timeline.length > 0 && (
        <div className="pt-3 border-t border-slate-800">
          <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
            Recorded Turnout Feed Logs
          </span>
          <div className="mt-2 space-y-2 max-h-36 overflow-y-auto pr-1">
            {timeline.map((item, idx) => (
              <div
                key={idx}
                className="p-2.5 rounded-xl bg-slate-950 border border-slate-800/80 flex items-start justify-between gap-3 text-xs"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
                    <span className="font-semibold text-white">{item.hour_interval}</span>
                    <span
                      className={`text-[10px] px-1.5 py-0.2 rounded font-medium ${
                        item.is_peaceful
                          ? 'bg-emerald-950 text-emerald-400 border border-emerald-800'
                          : 'bg-amber-950 text-amber-400 border border-amber-800'
                      }`}
                    >
                      {item.is_peaceful ? 'Peaceful' : 'Disrupted'}
                    </span>
                    <span className="text-slate-500 font-mono text-[10px]">
                      ~{item.estimated_voter_turnout} accredited
                    </span>
                  </div>
                  {item.quick_note && (
                    <p className="mt-1 text-slate-400 text-[11px] break-words">{item.quick_note}</p>
                  )}
                </div>
                <span className="text-[10px] text-slate-500 font-mono flex items-center gap-1 shrink-0">
                  <Clock className="w-3 h-3 text-slate-400" /> {item.timestamp}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* PROCEED TO STEP 4 BUTTON */}
      <div className="pt-3 border-t border-slate-800">
        <button
          type="button"
          onClick={handleProceed}
          className="w-full py-3 px-4 rounded-xl bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold text-xs shadow-md flex items-center justify-center gap-2 transition group"
        >
          <span>Proceed to Cutoff (2:30 PM)</span>
          <ArrowRight className="w-4 h-4 text-slate-950 group-hover:translate-x-1 transition" />
        </button>
        <p className="text-[10px] text-slate-400 text-center mt-1.5">
          Tap when voting approaches 2:30 PM cutoff.
        </p>
      </div>
    </div>
  );
};
