'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { locations } from '@/data/locations';
import { treatments, treatmentCategories } from '@/data/treatments';
import { useLanguage } from '@/context/LanguageContext';

type Step = 'select' | 'schedule' | 'personal' | 'confirm';

export default function OnlineBookingPage() {
  const { t } = useLanguage();

  // Step state
  const [step, setStep] = useState<Step>('select');

  // Step 1: Select
  const [selectedOutlet, setSelectedOutlet] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [selectedTreatment, setSelectedTreatment] = useState<string>('');

  // Step 2: Schedule
  const [selectedDate, setSelectedDate] = useState<string>('');
  const [selectedTime, setSelectedTime] = useState<string>('');

  // Step 3: Personal data
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [notes, setNotes] = useState('');

  // Submit state
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [error, setError] = useState('');

  // Get cities from locations
  const cities = [...new Set(locations.map((l) => l.city))].sort();

  // Filter locations by city (grouping)
  const groupedLocations = locations.reduce((acc, loc) => {
    if (!acc[loc.city]) acc[loc.city] = [];
    acc[loc.city].push(loc);
    return acc;
  }, {} as Record<string, typeof locations>);

  // Filter treatments by category
  const filteredTreatments = selectedCategory
    ? treatments.filter((t) => t.category === selectedCategory)
    : treatments;

  const selectedTreatmentData = treatments.find((t) => t.id === selectedTreatment);
  const selectedLocationData = locations.find((l) => l.name === selectedOutlet);

  const timeSlots = ['09:00', '10:00', '11:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'];

  const canProceedToSchedule = selectedOutlet && selectedCategory && selectedTreatment;
  const canProceedToPersonal = canProceedToSchedule && selectedDate && selectedTime;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!canProceedToPersonal) return;

    setIsSubmitting(true);
    setError('');

    try {
      const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
      const response = await fetch(`${apiUrl}/api/bookings`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name, phone, email,
          branch: selectedOutlet,
          category: selectedCategory,
          treatment: selectedTreatment,
          date: selectedDate,
          time: selectedTime,
          notes,
        }),
      });

      if (!response.ok) throw new Error('Gagal membuat reservasi');
      setIsSuccess(true);
    } catch (err) {
      setError('Gagal mengirim reservasi. Silakan coba lagi melalui WhatsApp.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const resetForm = () => {
    setStep('select');
    setSelectedOutlet('');
    setSelectedCategory('');
    setSelectedTreatment('');
    setSelectedDate('');
    setSelectedTime('');
    setName('');
    setPhone('');
    setEmail('');
    setNotes('');
    setIsSuccess(false);
    setError('');
  };

  const stepIndicator = (label: string, isActive: boolean, isDone: boolean, num: number) => (
    <div className={`flex items-center gap-2 ${isActive ? 'text-gold' : isDone ? 'text-green-600' : 'text-grey'}`}>
      <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold transition-all
        ${isActive ? 'bg-gold text-white' : isDone ? 'bg-green-500 text-white' : 'bg-blush text-espresso'}`}>
        {isDone ? '✓' : num}
      </div>
      <span className={`text-xs uppercase tracking-wider font-semibold hidden md:inline
        ${isActive ? 'text-gold' : isDone ? 'text-green-600' : 'text-grey'}`}>{label}</span>
    </div>
  );

  // Success state
  if (isSuccess) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <section className="py-24">
          <div className="container-custom max-w-lg mx-auto text-center">
            <div className="text-6xl mb-6">✅</div>
            <h1 className="font-cormorant text-4xl font-bold text-espresso mb-4">Reservasi Terkirim!</h1>
            <p className="text-grey-dark mb-4">Terima kasih, {name}!</p>
            <p className="text-grey-dark mb-8">Tim kami akan menghubungi Anda melalui WhatsApp dalam 1x24 jam untuk konfirmasi jadwal.</p>

            <div className="bg-white p-6 rounded-lg border border-blush text-left mb-8">
              <h3 className="font-semibold text-espresso mb-3">Detail Reservasi:</h3>
              <div className="space-y-2 text-sm text-grey-dark">
                <p><span className="font-semibold">Treatment:</span> {selectedTreatmentData?.name || selectedTreatment}</p>
                <p><span className="font-semibold">Cabang:</span> {selectedLocationData?.name || selectedOutlet}</p>
                <p><span className="font-semibold">Tanggal:</span> {selectedDate}</p>
                <p><span className="font-semibold">Jam:</span> {selectedTime}</p>
              </div>
            </div>

            <div className="flex gap-3 justify-center">
              <button onClick={resetForm} className="btn-primary">Buat Reservasi Baru</button>
              <Link href="/" className="btn-secondary">Kembali ke Home</Link>
            </div>
          </div>
        </section>
        <Footer />
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />

      {/* Hero */}
      <section className="relative py-16 md:py-24 bg-espresso overflow-hidden">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-4xl md:text-6xl font-bold mb-4 uppercase text-white">📅 Online Booking</h1>
          <p className="text-ivory/80 max-w-2xl mx-auto text-lg">Reservasi treatment Carla Skin Clinic secara online. Pilih cabang, jadwal, dan treatment dengan mudah.</p>
          <nav className="mt-4 text-xs tracking-widest uppercase text-white">
            <Link href="/" className="hover:text-gold transition text-white">Home</Link>
            <span className="mx-2 text-white">/</span>
            <span className="text-white/60">Online Booking</span>
          </nav>
        </div>
      </section>

      {/* Booking Form */}
      <section className="py-12 md:py-16">
        <div className="container-custom max-w-4xl">
          {/* Step Indicator */}
          <div className="flex items-center justify-center gap-4 md:gap-12 mb-12">
            {stepIndicator(t('contact.form.booking-detail'), step === 'select', step === 'schedule' || step === 'personal' || step === 'confirm', 1)}
            <div className={`h-px w-12 md:w-24 ${step === 'schedule' || step === 'personal' || step === 'confirm' ? 'bg-gold' : 'bg-blush'}`} />
            {stepIndicator('Jadwal', step === 'schedule', step === 'personal' || step === 'confirm', 2)}
            <div className={`h-px w-12 md:w-24 ${step === 'personal' || step === 'confirm' ? 'bg-gold' : 'bg-blush'}`} />
            {stepIndicator(t('contact.form.personal'), step === 'personal', step === 'confirm', 3)}
            <div className={`h-px w-12 md:w-24 ${step === 'confirm' ? 'bg-gold' : 'bg-blush'}`} />
            {stepIndicator('Konfirmasi', step === 'confirm', false, 4)}
          </div>

          <form onSubmit={handleSubmit}>
            {/* STEP 1: Select Outlet, Category, Treatment */}
            {step === 'select' && (
              <div className="bg-white p-8 rounded-lg border border-blush shadow-sm">
                <h2 className="font-cormorant text-2xl font-bold text-espresso mb-6">Pilih Cabang & Treatment</h2>

                {/* Outlet */}
                <div className="mb-6">
                  <label className="block text-sm font-semibold text-espresso mb-3">📍 Pilih Cabang *</label>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-48 overflow-y-auto">
                    {Object.entries(groupedLocations).map(([city, locs]) => (
                      <div key={city}>
                        <p className="text-xs text-grey font-semibold mb-1 uppercase">{city}</p>
                        {locs.map((loc) => (
                          <button
                            key={loc.id}
                            type="button"
                            onClick={() => setSelectedOutlet(loc.name)}
                            className={`w-full text-left p-3 rounded-lg border text-sm transition mb-1
                              ${selectedOutlet === loc.name ? 'bg-gold text-white border-gold' : 'bg-ivory border-blush text-espresso hover:bg-blush'}`}
                          >
                            {loc.name.replace('Carla Skin Clinic', '').trim() || loc.name}
                          </button>
                        ))}
                      </div>
                    ))}
                  </div>
                </div>

                {/* Category */}
                <div className="mb-6">
                  <label className="block text-sm font-semibold text-espresso mb-3">📂 Kategori Treatment *</label>
                  <div className="flex flex-wrap gap-2">
                    {treatmentCategories.map((cat) => (
                      <button
                        key={cat.id}
                        type="button"
                        onClick={() => { setSelectedCategory(cat.id); setSelectedTreatment(''); }}
                        className={`px-4 py-2 rounded-full text-sm font-semibold transition
                          ${selectedCategory === cat.id ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'}`}
                      >
                        {cat.icon} {cat.name}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Treatment */}
                <div className="mb-6">
                  <label className="block text-sm font-semibold text-espresso mb-3">💆 Pilih Treatment *</label>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-64 overflow-y-auto">
                    {filteredTreatments.map((tr) => (
                      <button
                        key={tr.id}
                        type="button"
                        onClick={() => setSelectedTreatment(tr.id)}
                        className={`w-full text-left p-4 rounded-lg border transition
                          ${selectedTreatment === tr.id ? 'bg-gold/10 border-gold ring-2 ring-gold/20' : 'bg-white border-blush hover:border-gold hover:shadow-sm'}`}
                      >
                        <p className="font-semibold text-espresso text-sm">{tr.icon} {tr.name}</p>
                        <p className="text-xs text-grey-dark mt-1">{tr.duration} · {tr.price}</p>
                      </button>
                    ))}
                  </div>
                </div>

                <div className="flex justify-end pt-4 border-t border-blush">
                  <button
                    type="button"
                    onClick={() => setStep('schedule')}
                    disabled={!canProceedToSchedule}
                    className="px-8 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark transition disabled:opacity-40 disabled:cursor-not-allowed"
                  >
                    Lanjut ke Jadwal →
                  </button>
                </div>
              </div>
            )}

            {/* STEP 2: Schedule */}
            {step === 'schedule' && (
              <div className="bg-white p-8 rounded-lg border border-blush shadow-sm">
                <h2 className="font-cormorant text-2xl font-bold text-espresso mb-6">Pilih Jadwal</h2>

                {/* Summary selected */}
                <div className="bg-ivory p-4 rounded-lg mb-6 space-y-1 text-sm">
                  <p><span className="font-semibold">Treatment:</span> {selectedTreatmentData?.name}</p>
                  <p><span className="font-semibold">Cabang:</span> {selectedLocationData?.name}</p>
                </div>

                {/* Date */}
                <div className="mb-6">
                  <label className="block text-sm font-semibold text-espresso mb-3">📅 Pilih Tanggal *</label>
                  <input
                    type="date"
                    value={selectedDate}
                    onChange={(e) => setSelectedDate(e.target.value)}
                    min={new Date().toISOString().split('T')[0]}
                    className="input-field w-full"
                    required
                  />
                </div>

                {/* Time */}
                <div className="mb-6">
                  <label className="block text-sm font-semibold text-espresso mb-3">⏰ Pilih Jam *</label>
                  <div className="grid grid-cols-3 md:grid-cols-5 gap-3">
                    {timeSlots.map((slot) => (
                      <button
                        key={slot}
                        type="button"
                        onClick={() => setSelectedTime(slot)}
                        className={`p-3 rounded-lg text-sm font-semibold border transition
                          ${selectedTime === slot ? 'bg-gold text-white border-gold' : 'bg-ivory border-blush text-espresso hover:bg-blush'}`}
                      >
                        {slot}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="flex justify-between pt-4 border-t border-blush">
                  <button type="button" onClick={() => setStep('select')} className="px-6 py-3 border border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold hover:text-white transition">
                    ← Kembali
                  </button>
                  <button
                    type="button"
                    onClick={() => setStep('personal')}
                    disabled={!selectedDate || !selectedTime}
                    className="px-8 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark transition disabled:opacity-40 disabled:cursor-not-allowed"
                  >
                    Lanjut ke Data Diri →
                  </button>
                </div>
              </div>
            )}

            {/* STEP 3: Personal Data */}
            {step === 'personal' && (
              <div className="bg-white p-8 rounded-lg border border-blush shadow-sm">
                <h2 className="font-cormorant text-2xl font-bold text-espresso mb-2">Data Diri</h2>
                <p className="text-grey-dark text-sm mb-6">Lengkapi data diri Anda untuk reservasi</p>

                {/* Summary */}
                <div className="bg-ivory p-4 rounded-lg mb-6 space-y-1 text-sm">
                  <p><span className="font-semibold">Treatment:</span> {selectedTreatmentData?.name} · {selectedTreatmentData?.price}</p>
                  <p><span className="font-semibold">Cabang:</span> {selectedLocationData?.name}</p>
                  <p><span className="font-semibold">Jadwal:</span> {selectedDate} · {selectedTime}</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                  <div>
                    <label className="block text-sm font-semibold text-espresso mb-1">Nama Lengkap *</label>
                    <input type="text" value={name} onChange={(e) => setName(e.target.value)} required className="input-field w-full" placeholder="Nama Anda" />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-espresso mb-1">No. WhatsApp *</label>
                    <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} required className="input-field w-full" placeholder="08xxxxxxxxxx" />
                  </div>
                  <div className="md:col-span-2">
                    <label className="block text-sm font-semibold text-espresso mb-1">Email</label>
                    <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="input-field w-full" placeholder="email@example.com" />
                  </div>
                  <div className="md:col-span-2">
                    <label className="block text-sm font-semibold text-espresso mb-1">Catatan (opsional)</label>
                    <textarea value={notes} onChange={(e) => setNotes(e.target.value)} className="input-field w-full min-h-[80px]" placeholder="Pesanan khusus, keluhan kulit, dll." />
                  </div>
                </div>

                {error && (
                  <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded text-red-600 text-sm">{error}</div>
                )}

                <div className="flex justify-between pt-4 border-t border-blush">
                  <button type="button" onClick={() => setStep('schedule')} className="px-6 py-3 border border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold hover:text-white transition">
                    ← Kembali
                  </button>
                  <button
                    type="button"
                    onClick={() => setStep('confirm')}
                    disabled={!name || !phone}
                    className="px-8 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark transition disabled:opacity-40 disabled:cursor-not-allowed"
                  >
                    Review Pesanan →
                  </button>
                </div>
              </div>
            )}

            {/* STEP 4: Confirm */}
            {step === 'confirm' && (
              <div className="bg-white p-8 rounded-lg border border-blush shadow-sm">
                <h2 className="font-cormorant text-2xl font-bold text-espresso mb-6">Konfirmasi Reservasi</h2>

                <div className="space-y-4 mb-6">
                  <div className="bg-ivory p-5 rounded-lg">
                    <h3 className="font-semibold text-gold text-sm uppercase tracking-wider mb-3">Detail Booking</h3>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between"><span className="text-grey-dark">Treatment</span><span className="font-semibold text-espresso">{selectedTreatmentData?.icon} {selectedTreatmentData?.name}</span></div>
                      <div className="flex justify-between"><span className="text-grey-dark">Cabang</span><span className="font-semibold text-espresso">{selectedLocationData?.name}</span></div>
                      <div className="flex justify-between"><span className="text-grey-dark">Durasi</span><span className="font-semibold text-espresso">{selectedTreatmentData?.duration}</span></div>
                      <div className="flex justify-between"><span className="text-grey-dark">Harga</span><span className="font-semibold text-gold">{selectedTreatmentData?.price}</span></div>
                    </div>
                  </div>

                  <div className="bg-ivory p-5 rounded-lg">
                    <h3 className="font-semibold text-gold text-sm uppercase tracking-wider mb-3">Jadwal</h3>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between"><span className="text-grey-dark">Tanggal</span><span className="font-semibold text-espresso">{selectedDate}</span></div>
                      <div className="flex justify-between"><span className="text-grey-dark">Jam</span><span className="font-semibold text-espresso">{selectedTime}</span></div>
                    </div>
                  </div>

                  <div className="bg-ivory p-5 rounded-lg">
                    <h3 className="font-semibold text-gold text-sm uppercase tracking-wider mb-3">Data Diri</h3>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between"><span className="text-grey-dark">Nama</span><span className="font-semibold text-espresso">{name}</span></div>
                      <div className="flex justify-between"><span className="text-grey-dark">No. WhatsApp</span><span className="font-semibold text-espresso">{phone}</span></div>
                      {email && <div className="flex justify-between"><span className="text-grey-dark">Email</span><span className="font-semibold text-espresso">{email}</span></div>}
                    </div>
                  </div>
                </div>

                <div className="flex justify-between pt-4 border-t border-blush">
                  <button type="button" onClick={() => setStep('personal')} className="px-6 py-3 border border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold hover:text-white transition">
                    ← Edit
                  </button>
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="px-10 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark transition flex items-center gap-2 disabled:opacity-40"
                  >
                    {isSubmitting ? (
                      <>
                        <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                        Memproses...
                      </>
                    ) : (
                      '✅ Konfirmasi Reservasi'
                    )}
                  </button>
                </div>
              </div>
            )}
          </form>
        </div>
      </section>

      <Footer />
    </main>
  );
}
