import React, { useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { mdiFlash, mdiDiceMultiple, mdiTrophy, mdiRefresh, mdiCheckDecagram } from '@mdi/js';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import LayoutGuest from '../layouts/Guest';
import BaseIcon from '../components/BaseIcon';
import SectionMain from '../components/SectionMain';
import { getPageTitle } from '../config';
import { useAppDispatch } from '../stores/hooks';
import { generateAutoTicket } from '../stores/tickets/ticketsSlice';

export default function Home() {
  const dispatch = useAppDispatch();
  const [targetOdds, setTargetOdds] = useState('2.50');
  const [gameCount, setGameCount] = useState('5');
  const [generatedTicket, setGeneratedTicket] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const handleGenerate = async () => {
    setLoading(true);
    try {
      const resultAction = await dispatch(generateAutoTicket({ desired_odds: targetOdds, game_count: gameCount }));
      if (generateAutoTicket.fulfilled.match(resultAction)) {
        setGeneratedTicket(resultAction.payload);
      }
    } catch (error) {
      console.error('Failed to generate ticket:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-slate-900 text-white">
      <Head>
        <title>{getPageTitle('BetMagic - Auto Ticket Generator')}</title>
      </Head>

      {/* Header */}
      <nav className="flex items-center justify-between px-6 py-4 bg-slate-800/50 backdrop-blur-md sticky top-0 z-50">
        <div className="flex items-center space-x-2">
          <BaseIcon path={mdiFlash} size={32} className="text-green-500" />
          <span className="text-2xl font-bold tracking-tighter">BET<span className="text-green-500">MAGIC</span></span>
        </div>
        <div className="flex items-center space-x-4">
          <Link href="/login" className="text-sm font-medium hover:text-green-400 transition-colors">
            Login
          </Link>
          <BaseButton href="/login" label="Join Now" color="success" className="rounded-full px-6" />
        </div>
      </nav>

      {/* Hero Section */}
      <section className="relative pt-20 pb-32 px-6 overflow-hidden">
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-full h-full -z-10">
          <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[800px] bg-green-500/10 rounded-full blur-[120px]" />
          <div className="absolute bottom-0 right-0 w-[400px] h-[400px] bg-blue-500/10 rounded-full blur-[100px]" />
        </div>

        <div className="max-w-6xl mx-auto grid lg:grid-cols-2 gap-12 items-center">
          <div className="space-y-8 text-center lg:text-left">
            <h1 className="text-5xl lg:text-7xl font-extrabold leading-tight">
              Build Your <span className="text-transparent bg-clip-text bg-gradient-to-r from-green-400 to-emerald-600">Dream Ticket</span> in Seconds.
            </h1>
            <p className="text-xl text-slate-400 max-w-xl mx-auto lg:mx-0">
              Stop wasting hours searching for games. Our smart algorithm finds the best odds based on your target and builds your winning ticket instantly.
            </p>
            <div className="flex flex-col sm:flex-row items-center justify-center lg:justify-start space-y-4 sm:space-y-0 sm:space-x-4">
              <BaseButton label="Get Started Free" color="success" className="px-8 py-3 text-lg rounded-full shadow-lg shadow-green-500/20" />
              <div className="flex items-center space-x-2 text-slate-400">
                <BaseIcon path={mdiCheckDecagram} className="text-green-500" />
                <span className="text-sm font-medium">10,000+ Tickets Generated Today</span>
              </div>
            </div>
          </div>

          {/* Generator Widget */}
          <div className="relative">
            <CardBox className="bg-slate-800/80 border-slate-700 backdrop-blur-xl shadow-2xl overflow-hidden">
              <div className="p-6 space-y-6">
                <div className="flex items-center space-x-3 mb-4">
                  <div className="bg-green-500/20 p-2 rounded-lg">
                    <BaseIcon path={mdiDiceMultiple} className="text-green-500" />
                  </div>
                  <h3 className="text-xl font-bold">Quick Generator</h3>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <label className="text-xs font-bold text-slate-500 uppercase tracking-wider">Target Odds</label>
                    <div className="relative">
                      <input
                        type="text"
                        value={targetOdds}
                        onChange={(e) => setTargetOdds(e.target.value)}
                        className="w-full bg-slate-900/50 border border-slate-700 rounded-xl px-4 py-3 text-2xl font-bold text-green-400 focus:outline-none focus:border-green-500 transition-colors"
                      />
                      <span className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-500 font-bold text-sm">x</span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-xs font-bold text-slate-500 uppercase tracking-wider">Game Count</label>
                    <div className="relative">
                      <input
                        type="number"
                        value={gameCount}
                        onChange={(e) => setGameCount(e.target.value)}
                        className="w-full bg-slate-900/50 border border-slate-700 rounded-xl px-4 py-3 text-2xl font-bold focus:outline-none focus:border-green-500 transition-colors"
                      />
                    </div>
                  </div>
                </div>

                <button
                  onClick={handleGenerate}
                  disabled={loading}
                  className={`w-full py-4 rounded-xl font-bold text-lg flex items-center justify-center space-x-2 transition-all shadow-lg ${
                    loading 
                      ? 'bg-slate-700 cursor-not-allowed' 
                      : 'bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-400 hover:to-emerald-500 shadow-green-500/20 active:scale-[0.98]'
                  }`}
                >
                  {loading ? (
                    <BaseIcon path={mdiRefresh} className="animate-spin" />
                  ) : (
                    <>
                      <BaseIcon path={mdiTrophy} />
                      <span>Generate Magic Ticket</span>
                    </>
                  )}
                </button>

                {/* Result Area */}
                {generatedTicket && (
                  <div className="mt-6 space-y-4 animate-fade-in">
                    <div className="flex items-center justify-between border-b border-slate-700 pb-2">
                      <span className="text-slate-400 font-medium">Generated Selections</span>
                      <span className="text-green-400 font-bold">Total Odds: {generatedTicket.totalOdds.toFixed(2)}x</span>
                    </div>
                    <div className="space-y-3 max-h-[300px] overflow-y-auto pr-2 custom-scrollbar">
                      {generatedTicket.selections.map((sel: any, idx: number) => (
                        <div key={idx} className="bg-slate-900/80 p-3 rounded-lg border border-slate-700/50 flex justify-between items-center group hover:border-green-500/30 transition-colors">
                          <div className="space-y-1">
                            <p className="text-xs text-slate-500 font-bold uppercase">{sel.market?.game?.title || 'Unknown Match'}</p>
                            <p className="font-bold text-sm">{sel.name}</p>
                            <p className="text-[10px] text-slate-400">{sel.market?.name}</p>
                          </div>
                          <div className="text-right">
                            <span className="bg-slate-800 text-green-400 px-2 py-1 rounded text-xs font-bold border border-slate-700 group-hover:border-green-500/50">
                              {parseFloat(sel.odds).toFixed(2)}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                    <BaseButton
                        href='/login'
                        label='Save This Ticket'
                        color='info'
                        className='w-full rounded-xl mt-2'
                    />
                  </div>
                )}
              </div>
            </CardBox>
          </div>
        </div>
      </section>

      {/* Feature Section */}
      <section className="bg-slate-800/30 py-24 px-6">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-16 space-y-4">
            <h2 className="text-3xl md:text-4xl font-extrabold tracking-tight">Why BetMagic?</h2>
            <p className="text-slate-400">Our platform is designed for professional and casual bettors alike.</p>
          </div>

          <div className="grid md:grid-cols-3 gap-8">
            {[
              { icon: mdiFlash, title: 'Lightning Fast', desc: 'Generate tickets in under 1 second using our optimized selection engine.' },
              { icon: mdiTrophy, title: 'Highest Success', desc: 'We only pick selections from verified markets with live data integration.' },
              { icon: mdiRefresh, title: 'Always Fresh', desc: 'Game data and odds are updated in real-time to ensure your ticket is valid.' }
            ].map((feature, i) => (
              <div key={i} className="bg-slate-800/50 p-8 rounded-3xl border border-slate-700/50 hover:border-green-500/30 transition-all hover:-translate-y-2">
                <div className="bg-green-500/10 w-12 h-12 rounded-2xl flex items-center justify-center mb-6">
                  <BaseIcon path={feature.icon} className="text-green-500" />
                </div>
                <h4 className="text-xl font-bold mb-3">{feature.title}</h4>
                <p className="text-slate-400 leading-relaxed">{feature.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="border-t border-slate-800 py-12 px-6">
        <div className="max-w-6xl mx-auto flex flex-col md:flex-row justify-between items-center space-y-6 md:space-y-0">
          <div className="flex items-center space-x-2">
            <BaseIcon path={mdiFlash} size={24} className="text-green-500" />
            <span className="text-xl font-bold">BETMAGIC</span>
          </div>
          <p className="text-slate-500 text-sm">© 2026 BetMagic AI. Responsible betting encouraged.</p>
          <div className="flex space-x-6">
            <Link href="/privacy-policy" className="text-sm text-slate-400 hover:text-white transition-colors">Privacy</Link>
            <Link href="/terms" className="text-sm text-slate-400 hover:text-white transition-colors">Terms</Link>
          </div>
        </div>
      </footer>

      <style jsx global>{`
        .animate-fade-in {
          animation: fadeIn 0.5s ease-out forwards;
        }
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: translateY(0); }
        }
        .custom-scrollbar::-webkit-scrollbar {
          width: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: transparent;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #334155;
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #475569;
        }
      `}</style>
    </div>
  );
}

Home.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};