import { useState } from 'react';
import { format } from 'date-fns';
import { hu } from 'date-fns/locale';
import { Calendar as CalendarIcon, CheckCircle2, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import foglalas from '@/public/foglalas.png';

type SubmissionStatus = 'idle' | 'error' | 'success' | 'loading';

export default function Reservations() {
  const [date, setDate] = useState<Date | undefined>();
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    partySize: '',
    time: '18:00',
  });
  const [status, setStatus] = useState<SubmissionStatus>('idle');
  const [message, setMessage] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSelectChange = (name: 'partySize') => (value: string) => {
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setMessage('');

    if (!date || !formData.name || !formData.email || !formData.partySize || !formData.time) {
      setMessage('Kérjük, töltse ki az összes mezőt a folytatáshoz.');
      setStatus('error');
      return;
    }

    setStatus('loading');

    setTimeout(() => {
      const reservationData = {
        ...formData,
        date: format(date, 'yyyy-MM-dd'),
      };
      console.log('Foglalási adatok:', reservationData);

      setStatus('success');
      setMessage(`Köszönjük a foglalást, ${formData.name}! Hamarosan emailben is megerősítjük.`);
    }, 1000);
  };

  const resetForm = () => {
    setFormData({ name: '', email: '', partySize: '', time: '18:00' });
    setDate(undefined);
    setStatus('idle');
    setMessage('');
  };

  return (
    <section id="foglalas" className="scroll-mt-20 bg-slate-900 py-24 sm:py-32">
      <div className="container mx-auto grid grid-cols-1 items-center gap-x-16 gap-y-12 px-6 lg:grid-cols-2">
        <div className="text-center lg:text-left">
          <h2 className="text-4xl font-bold tracking-tight text-amber-400">Foglaljon Asztalt</h2>
          <p className="mt-4 text-lg leading-8 text-slate-300">
            Biztosítsa helyét egy felejthetetlen gasztronómiai élményhez. Örömmel látjuk vendégül!
          </p>
          <img
            src={foglalas}
            alt="Hangulatos étterem belső tere asztalokkal"
            className="mt-8 w-full rounded-lg object-cover shadow-2xl"
          />
        </div>

        <div className="flex min-h-[550px] items-center justify-center rounded-lg bg-slate-950 p-8 shadow-2xl">
          {status === 'success' ? (
            <div className="text-center">
              <CheckCircle2 className="mx-auto h-16 w-16 text-green-500" />
              <h3 className="mt-4 text-2xl font-semibold text-white">Foglalás elküldve!</h3>
              <p className="mt-2 text-slate-300">{message}</p>
              <Button onClick={resetForm} size="lg" className="mt-8 bg-amber-500 text-slate-900 hover:bg-amber-400">
                Új foglalás
              </Button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="flex w-full flex-col space-y-6">
              <div className="grid w-full items-center gap-1.5">
                <Label htmlFor="name">Teljes Név</Label>
                <Input id="name" name="name" value={formData.name} onChange={handleChange} />
              </div>

              <div className="grid w-full items-center gap-1.5">
                <Label htmlFor="email">Email Cím</Label>
                <Input id="email" name="email" type="email" value={formData.email} onChange={handleChange} />
              </div>

              <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                <div className="grid w-full items-center gap-1.5">
                  <Label>Vendégek száma</Label>
                  <Select onValueChange={handleSelectChange('partySize')} value={formData.partySize}>
                    <SelectTrigger><SelectValue placeholder="Válasszon..." /></SelectTrigger>
                    <SelectContent className="dark">
                      <SelectItem value="1">1 fő</SelectItem>
                      <SelectItem value="2">2 fő</SelectItem>
                      <SelectItem value="3">3 fő</SelectItem>
                      <SelectItem value="4">4 fő</SelectItem>
                      <SelectItem value="5+">5+ fő</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="grid w-full items-center gap-1.5">
                  <Label htmlFor="time">Időpont</Label>
                  <Input id="time" name="time" type="time" value={formData.time} onChange={handleChange} />
                </div>
              </div>

              <div className="grid w-full items-center gap-1.5">
                <Label>Dátum</Label>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button variant={'outline'} className={cn('w-full justify-start text-left font-normal', !date && 'text-muted-foreground')}>
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {date ? format(date, 'PPP', { locale: hu }) : <span>Válasszon dátumot</span>}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="dark w-auto p-0">
                    <Calendar mode="single" selected={date} onSelect={setDate} autoFocus disabled={(day) => day < new Date(new Date().setDate(new Date().getDate() - 1))} />
                  </PopoverContent>
                </Popover>
              </div>

              <div className="h-14">
                {status === 'error' && message && (
                  <div className="flex items-center space-x-2 rounded-md border border-red-500/50 bg-red-500/10 p-3 text-sm text-red-400">
                    <AlertTriangle className="h-4 w-4 flex-shrink-0" />
                    <p>{message}</p>
                  </div>
                )}
              </div>

              <Button type="submit" size="lg" className="w-full bg-amber-500 text-slate-900 hover:bg-amber-400 !mt-8" disabled={status === 'loading'}>
                {status === 'loading' ? 'Küldés...' : 'Asztalfoglalás'}
              </Button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}
