'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, Ticket, Clock, Users, Heart, Zap, MapPin,
  CheckCircle, AlertTriangle, Shield, RotateCcw
} from 'lucide-react';

type Phase = 'setup' | 'waiting' | 'queue' | 'scanning' | 'found' | 'secured';

interface SeatOption {
  section: string;
  row: string;
  seats: string;
  price: number;
  quality: 'Premium' | 'Great' | 'Good';
  together: boolean;
}

const VENUE_SECTIONS = [
  'Floor A', 'Floor B', 'Lower 101', 'Lower 102', 'Lower 103',
  'Lower 104', 'Mezzanine 201', 'Mezzanine 202', 'Upper 301', 'Upper 302'
];

function generateSeats(): SeatOption[] {
  const options: SeatOption[] = [];
  const count = 3 + Math.floor(Math.random() * 3);
  for (let i = 0; i < count; i++) {
    const section = VENUE_SECTIONS[Math.floor(Math.random() * VENUE_SECTIONS.length)];
    const row = String.fromCharCode(65 + Math.floor(Math.random() * 15));
    const seatNum = 1 + Math.floor(Math.random() * 30);
    const price = section.includes('Floor') ? 180 + Math.floor(Math.random() * 120) : section.includes('Lower') ? 120 + Math.floor(Math.random() * 80) : 60 + Math.floor(Math.random() * 60);
    options.push({
      section, row, seats: `${seatNum}-${seatNum + 1}`,
      price, quality: section.includes('Floor') ? 'Premium' : section.includes('Lower') ? 'Great' : 'Good',
      together: true,
    });
  }
  return options.sort((a, b) => b.price - a.price);
}

export default function TicketGhostPage() {
  const [phase, setPhase] = useState<Phase>('setup');
  const [event, setEvent] = useState('Taylor Swift — Eras Tour 2026');
  const [venue, setVenue] = useState('Madison Square Garden, NYC');
  const [date, setDate] = useState('2026-08-15');
  const [maxPrice, setMaxPrice] = useState(250);
  const [preference, setPreference] = useState<'floor' | 'lower' | 'any'>('lower');
  const [partnerName, setPartnerName] = useState('');
  const [queuePosition, setQueuePosition] = useState(0);
  const [queueTotal, setQueueTotal] = useState(0);
  const [scanCount, setScanCount] = useState(0);
  const [seats, setSeats] = useState<SeatOption[]>([]);
  const [selectedSeat, setSelectedSeat] = useState<SeatOption | null>(null);
  const [logs, setLogs] = useState<string[]>([]);
  const logsRef = useRef<HTMLDivElement>(null);

  const addLog = useCallback((msg: string) => {
    setLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`]);
  }, []);

  useEffect(() => {
    if (logsRef.current) logsRef.current.scrollTop = logsRef.current.scrollHeight;
  }, [logs]);

  const startWatch = useCallback(() => {
    setPhase('waiting');
    setLogs([]);
    addLog('\u{1f47b} TicketGhost activated. Monitoring ticket release...');
    addLog(`\u{1f3a4} Event: ${event}`);
    addLog(`\u{1f4cd} Venue: ${venue}`);
    addLog(`\u{1f4b0} Max budget: $${maxPrice} per ticket \u00d7 2 seats`);
    addLog(`\u{1f4a1} Preference: ${preference === 'floor' ? 'Floor seats' : preference === 'lower' ? 'Lower bowl' : 'Best available'}`);
    if (partnerName) addLog(`\u{2764}\ufe0f Securing 2 adjacent seats for you & ${partnerName}`);

    // Simulate countdown
    setTimeout(() => {
      addLog('\u23f0 Tickets go on sale in 10 seconds...');
      setTimeout(() => {
        addLog('\u23f0 5 seconds...');
        setTimeout(() => {
          addLog('\u23f0 3... 2... 1...');
          setTimeout(() => {
            addLog('\u{1f6a8} TICKETS ARE LIVE! Entering queue...');
            setPhase('queue');
            const total = 8000 + Math.floor(Math.random() * 15000);
            const pos = 200 + Math.floor(Math.random() * 3000);
            setQueueTotal(total);
            setQueuePosition(pos);
            addLog(`\u{1f465} Queue position: ${pos.toLocaleString()} of ${total.toLocaleString()}`);
          }, 1500);
        }, 2000);
      }, 3000);
    }, 2000);
  }, [event, venue, maxPrice, preference, partnerName, addLog]);

  // Queue advancement
  useEffect(() => {
    if (phase !== 'queue') return;
    const interval = setInterval(() => {
      setQueuePosition(prev => {
        const next = Math.max(1, prev - (50 + Math.floor(Math.random() * 200)));
        if (next <= 1) {
          clearInterval(interval);
          addLog('\u2705 Front of queue! Scanning available seats...');
          setPhase('scanning');
          return 1;
        }
        if (next < prev - 300) addLog(`\u{1f465} Queue advancing... Position: ${next.toLocaleString()}`);
        return next;
      });
    }, 800);
    return () => clearInterval(interval);
  }, [phase, addLog]);

  // Scanning simulation
  useEffect(() => {
    if (phase !== 'scanning') return;
    setScanCount(0);
    const msgs = [
      'Scanning Floor sections...', 'Checking Lower Bowl availability...',
      'Filtering for 2 adjacent seats...', 'Verifying price range...',
      'Cross-referencing seat quality ratings...', 'Found candidates! Locking best options...'
    ];
    let idx = 0;
    const interval = setInterval(() => {
      setScanCount(prev => prev + 30 + Math.floor(Math.random() * 50));
      if (idx < msgs.length) { addLog(`\u{1f50d} ${msgs[idx]}`); idx++; }
      if (idx >= msgs.length) {
        clearInterval(interval);
        const found = generateSeats();
        setSeats(found);
        addLog(`\u{1f389} Found ${found.length} pairs of adjacent seats within budget!`);
        setPhase('found');
      }
    }, 700);
    return () => clearInterval(interval);
  }, [phase, addLog]);

  const secureSeat = useCallback((seat: SeatOption) => {
    setSelectedSeat(seat);
    addLog(`\u{1f512} Locking ${seat.section} Row ${seat.row} Seats ${seat.seats}...`);
    addLog(`\u{1f4b3} Processing $${seat.price * 2} for 2 tickets...`);
    setTimeout(() => {
      addLog('\u2705 TICKETS SECURED! Confirmation sent.');
      setPhase('secured');
    }, 1500);
  }, [addLog]);

  const reset = useCallback(() => {
    setPhase('setup');
    setLogs([]);
    setSeats([]);
    setSelectedSeat(null);
    setScanCount(0);
  }, []);

  const qualityColor = (q: string) => q === 'Premium' ? 'text-amber-400' : q === 'Great' ? 'text-sky-400' : 'text-gray-400';

  return (
    <main className="min-h-screen bg-[#0C1222]">
      <div className="max-w-5xl mx-auto px-6 py-8">
        <Link href="/demos" className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-300 text-sm mb-8 transition-colors">
          <ArrowLeft className="w-4 h-4" /> Back to Demos
        </Link>

        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-pink-500/10 border border-pink-500/20 flex items-center justify-center">
              <Ticket className="w-5 h-5 text-pink-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">TicketGhost</h1>
              <p className="text-gray-500 text-sm">Automated concert ticket watch &amp; secure for couples</p>
            </div>
            {phase !== 'setup' && (
              <button onClick={reset} className="ml-auto flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-300 transition-colors">
                <RotateCcw className="w-3 h-3" /> Reset
              </button>
            )}
          </div>
        </motion.div>

        <div className="grid lg:grid-cols-5 gap-6">
          {/* Left: Setup / Status */}
          <div className="lg:col-span-3 space-y-6">
            {phase === 'setup' && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6 space-y-4">
                <h2 className="text-sm font-semibold text-white flex items-center gap-2"><Zap className="w-4 h-4 text-pink-400" /> Configure Watch</h2>
                <div className="grid md:grid-cols-2 gap-4">
                  <div><label className="text-xs text-gray-400 mb-1 block">Event</label><input value={event} onChange={e => setEvent(e.target.value)} className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-pink-500 focus:outline-none" /></div>
                  <div><label className="text-xs text-gray-400 mb-1 block">Venue</label><input value={venue} onChange={e => setVenue(e.target.value)} className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-pink-500 focus:outline-none" /></div>
                  <div><label className="text-xs text-gray-400 mb-1 block">Date</label><input type="date" value={date} onChange={e => setDate(e.target.value)} className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-pink-500 focus:outline-none" /></div>
                  <div><label className="text-xs text-gray-400 mb-1 block">Max Price (per ticket)</label><input type="number" value={maxPrice} onChange={e => setMaxPrice(parseInt(e.target.value) || 0)} className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-pink-500 focus:outline-none" /></div>
                  <div><label className="text-xs text-gray-400 mb-1 block">Your Date\u2019s Name \u2764\ufe0f</label><input value={partnerName} onChange={e => setPartnerName(e.target.value)} placeholder="Optional" className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-pink-500 focus:outline-none" /></div>
                  <div>
                    <label className="text-xs text-gray-400 mb-1 block">Seat Preference</label>
                    <select value={preference} onChange={e => setPreference(e.target.value as 'floor' | 'lower' | 'any')} className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-pink-500 focus:outline-none">
                      <option value="floor" className="bg-gray-900">Floor Seats (Premium)</option>
                      <option value="lower" className="bg-gray-900">Lower Bowl (Best Value)</option>
                      <option value="any" className="bg-gray-900">Best Available</option>
                    </select>
                  </div>
                </div>
                <button onClick={startWatch} className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-pink-500/80 to-orange-500/80 hover:from-pink-500 hover:to-orange-500 text-white font-medium text-sm transition-all">
                  <Ticket className="w-4 h-4" /> Activate TicketGhost
                </button>
              </motion.div>
            )}

            {/* Live Status */}
            {phase !== 'setup' && (
              <div className="space-y-4">
                {/* Phase Indicator */}
                <div className="bg-black/40 border border-slate-800 rounded-xl p-4">
                  <div className="flex items-center gap-3">
                    {phase === 'secured' ? <CheckCircle className="w-5 h-5 text-emerald-400" /> : <div className="w-5 h-5 border-2 border-pink-400/30 border-t-pink-400 rounded-full animate-spin" />}
                    <div>
                      <p className="text-white text-sm font-medium">
                        {phase === 'waiting' && 'Waiting for ticket release...'}
                        {phase === 'queue' && `In queue: ${queuePosition.toLocaleString()} of ${queueTotal.toLocaleString()}`}
                        {phase === 'scanning' && `Scanning seats... (${scanCount} checked)`}
                        {phase === 'found' && `${seats.length} pairs found! Select your seats.`}
                        {phase === 'secured' && '\u{1f389} Tickets secured!'}
                      </p>
                      <p className="text-xs text-gray-500">{event} \u2022 {venue}</p>
                    </div>
                    <div className="ml-auto flex items-center gap-1.5">
                      <Users className="w-3 h-3 text-pink-400" />
                      <span className="text-xs text-pink-400">2 seats</span>
                      {partnerName && <Heart className="w-3 h-3 text-pink-400 ml-1" />}
                    </div>
                  </div>
                  {phase === 'queue' && (
                    <div className="mt-3 h-2 bg-black/30 rounded-full overflow-hidden">
                      <motion.div className="h-full bg-gradient-to-r from-pink-500 to-orange-500 rounded-full" animate={{ width: `${Math.max(5, 100 - (queuePosition / queueTotal) * 100)}%` }} transition={{ duration: 0.5 }} />
                    </div>
                  )}
                </div>

                {/* Seat Selection */}
                <AnimatePresence>
                  {phase === 'found' && seats.length > 0 && (
                    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-2">
                      <h3 className="text-sm text-white font-semibold">Available Pairs (2 adjacent seats)</h3>
                      {seats.map((seat, i) => (
                        <button key={i} onClick={() => secureSeat(seat)} className="w-full flex items-center gap-4 px-4 py-3 rounded-xl bg-white/[0.02] border border-slate-800/50 hover:bg-white/[0.05] hover:border-pink-500/30 transition-all text-left">
                          <MapPin className={`w-4 h-4 ${qualityColor(seat.quality)}`} />
                          <div className="flex-1">
                            <div className="flex items-center gap-2">
                              <span className="text-sm text-white font-medium">{seat.section}</span>
                              <span className="text-xs text-gray-500">Row {seat.row} \u2022 Seats {seat.seats}</span>
                              <span className={`text-[10px] px-1.5 py-0.5 rounded ${seat.quality === 'Premium' ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20' : seat.quality === 'Great' ? 'bg-sky-500/10 text-sky-400 border border-sky-500/20' : 'bg-gray-500/10 text-gray-400 border border-gray-500/20'}`}>{seat.quality}</span>
                            </div>
                          </div>
                          <span className="text-white font-mono text-sm">${seat.price} \u00d7 2</span>
                        </button>
                      ))}
                    </motion.div>
                  )}
                </AnimatePresence>

                {/* Secured Confirmation */}
                <AnimatePresence>
                  {phase === 'secured' && selectedSeat && (
                    <motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} className="bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-6 text-center">
                      <CheckCircle className="w-12 h-12 text-emerald-400 mx-auto mb-3" />
                      <h3 className="text-xl font-bold text-white mb-1">Tickets Secured! 🎉</h3>
                      <p className="text-gray-400 text-sm mb-4">{event}</p>
                      <div className="inline-flex flex-col items-center gap-1 bg-black/30 rounded-xl px-6 py-4">
                        <span className="text-xs text-gray-500">Your Seats</span>
                        <span className="text-lg text-white font-bold">{selectedSeat.section} \u2022 Row {selectedSeat.row} \u2022 Seats {selectedSeat.seats}</span>
                        <span className="text-sm text-emerald-400 font-mono">${selectedSeat.price * 2} total for 2 tickets</span>
                        {partnerName && <span className="text-xs text-pink-400 mt-1">\u2764\ufe0f {partnerName} &amp; You \u2014 side by side</span>}
                      </div>
                      <p className="text-[10px] text-gray-600 mt-4 flex items-center justify-center gap-1"><Shield className="w-3 h-3" /> This is a concept demo \u2014 no actual tickets were purchased</p>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            )}
          </div>

          {/* Right: Activity Log */}
          <div className="lg:col-span-2">
            <div className="bg-black/40 border border-slate-800 rounded-xl overflow-hidden sticky top-8">
              <div className="px-4 py-2 border-b border-slate-800/50 flex items-center gap-2">
                <div className={`w-2 h-2 rounded-full ${phase === 'setup' ? 'bg-gray-600' : phase === 'secured' ? 'bg-emerald-400' : 'bg-pink-400 animate-pulse'}`} />
                <span className="text-xs text-gray-500">Activity Log</span>
              </div>
              <div ref={logsRef} className="h-[400px] overflow-y-auto p-3 space-y-1 font-mono text-[11px]">
                {logs.length === 0 && <p className="text-gray-700">Configure and activate to begin...</p>}
                {logs.map((log, i) => (
                  <motion.div key={i} initial={{ opacity: 0, x: -5 }} animate={{ opacity: 1, x: 0 }} className="text-gray-400">{log}</motion.div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="text-center mt-12 text-gray-700 text-xs">
          Concept demo \u2014 no actual ticket purchases \u2022 Built by The Hearth \u2022 <Link href="/demos" className="text-sky-500/50 hover:text-sky-400">View all demos</Link>
        </div>
      </div>
    </main>
  );
}
