'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { callFunction } from '@/lib/firebase';
import { useAuth } from '@/components/auth-provider';
import { ArrowLeft, Calendar, Lock, Unlock, Users, Camera, Check, Loader2 } from 'lucide-react';
import { toast } from '@/hooks/use-toast';
import { useLanguage } from '@/hooks/use-language';
import { t } from '@/lib/i18n';

interface EventTemplate {
  id: string;
  emoji: string;
  name: string;
  description: string;
  eventType: string;
  maxPhotosPerGuest: number;
  requireHostApproval: boolean;
  isPrivate: boolean;
  allowGuestSharing: boolean;
}

export default function CreateEventPage() {
  const router = useRouter();
  const { user } = useAuth();
  const { lang } = useLanguage();

  const templates: EventTemplate[] = [
    {
      id: 'classic_wedding',
      emoji: '💍',
      name: t(lang, 'classicWedding'),
      description: t(lang, 'classicWeddingDesc'),
      eventType: 'wedding',
      maxPhotosPerGuest: 20,
      requireHostApproval: true,
      isPrivate: true,
      allowGuestSharing: true,
    },
    {
      id: 'birthday_bash',
      emoji: '🎂',
      name: t(lang, 'birthdayBash'),
      description: t(lang, 'birthdayBashDesc'),
      eventType: 'birthday',
      maxPhotosPerGuest: 50,
      requireHostApproval: false,
      isPrivate: false,
      allowGuestSharing: true,
    },
    {
      id: 'adventure_trip',
      emoji: '✈️',
      name: t(lang, 'adventureTrip'),
      description: t(lang, 'adventureTripDesc'),
      eventType: 'trip',
      maxPhotosPerGuest: 30,
      requireHostApproval: false,
      isPrivate: true,
      allowGuestSharing: true,
    },
    {
      id: 'corporate_event',
      emoji: '🏢',
      name: t(lang, 'corporateEvent'),
      description: t(lang, 'corporateEventDesc'),
      eventType: 'corporate',
      maxPhotosPerGuest: 10,
      requireHostApproval: true,
      isPrivate: true,
      allowGuestSharing: false,
    },
    {
      id: 'graduation',
      emoji: '🎓',
      name: t(lang, 'graduationDay'),
      description: t(lang, 'graduationDayDesc'),
      eventType: 'graduation',
      maxPhotosPerGuest: 25,
      requireHostApproval: false,
      isPrivate: false,
      allowGuestSharing: true,
    },
    {
      id: 'engagement',
      emoji: '💖',
      name: t(lang, 'engagementParty'),
      description: t(lang, 'engagementPartyDesc'),
      eventType: 'engagement',
      maxPhotosPerGuest: 30,
      requireHostApproval: true,
      isPrivate: true,
      allowGuestSharing: true,
    },
  ];
  
  const eventTypes = [
    { id: 'wedding', emoji: '💍', label: t(lang, 'wedding') },
    { id: 'birthday', emoji: '🎂', label: t(lang, 'birthday') },
    { id: 'trip', emoji: '✈️', label: t(lang, 'trip') },
    { id: 'party', emoji: '🎉', label: t(lang, 'party') },
    { id: 'corporate', emoji: '🏢', label: t(lang, 'corporate') },
    { id: 'other', emoji: '📸', label: t(lang, 'other') },
  ];
  
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    name: '',
    description: '',
    eventType: 'wedding',
    startDate: '',
    endDate: '',
    revealDate: '',
    maxPhotosPerGuest: 10,
    maxGuests: 50,
    isPrivate: true,
    requireHostApproval: false,
    allowGuestSharing: true,
    autoApproveTrustedGuests: false,
    allowCoHost: false,
    watermarkText: 'Momira — momira.app',
  });

  const handleCreate = async () => {
    if (!form.name || !form.startDate) {
      toast({ title: t(lang, 'fillRequiredFields'), variant: 'destructive' });
      return;
    }
    if (!user) {
      toast({ title: t(lang, 'signInFirst'), variant: 'destructive' });
      router.push('/auth?redirect=/event/create');
      return;
    }
    setLoading(true);
    try {
      const createEventFn = callFunction('createEvent');
      const result = await createEventFn({
        name: form.name,
        description: form.description,
        eventType: form.eventType,
        hostName: user.displayName || user.phoneNumber || 'Host',
        startDate: form.startDate,
        endDate: form.endDate,
        revealDate: form.revealDate,
        maxPhotosPerGuest: form.maxPhotosPerGuest,
        maxGuests: form.maxGuests,
        isPrivate: form.isPrivate,
        allowGuestSharing: form.allowGuestSharing,
        requireHostApproval: form.requireHostApproval,
        watermarkText: form.watermarkText,
      });
      const { eventId } = result.data as any;
      toast({ title: t(lang, 'eventCreated'), variant: 'success' });
      router.push(`/event/${eventId}`);
    } catch (error: any) {
      console.error('Create event error:', error);
      toast({ title: error.message || t(lang, 'failedCreateEvent'), variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  const updateForm = (key: string, value: any) => {
    setForm((prev) => ({ ...prev, [key]: value }));
  };

  const applyTemplate = (template: EventTemplate) => {
    setForm((prev) => ({
      ...prev,
      name: prev.name || template.name,
      description: prev.description || template.description,
      eventType: template.eventType,
      maxPhotosPerGuest: template.maxPhotosPerGuest,
      requireHostApproval: template.requireHostApproval,
      isPrivate: template.isPrivate,
      allowGuestSharing: template.allowGuestSharing,
    }));
    toast({ title: `Applied: ${template.name}`, variant: 'success' });
  };

  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-50 border-b border-zinc-900 bg-background/80 backdrop-blur-md">
        <div className="max-w-xl mx-auto px-4 h-14 flex items-center justify-between">
          <Link href="/dashboard" className="inline-flex items-center gap-2 text-zinc-500 hover:text-zinc-300 text-sm">
            <ArrowLeft className="h-4 w-4" />
            {t(lang, 'cancel')}
          </Link>
          <h1 className="text-sm font-semibold">{t(lang, 'createEvent')}</h1>
          <div className="w-16" />
        </div>
      </header>

      <main className="max-w-xl mx-auto px-4 py-8">
        {/* Progress */}
        <div className="flex items-center gap-2 mb-8">
          {[1, 2, 3].map((s) => (
            <div
              key={s}
              className={`h-1 flex-1 rounded-full transition-colors ${
                s <= step ? 'bg-white' : 'bg-zinc-800'
              }`}
            />
          ))}
        </div>

        {step === 1 && (
          <div className="space-y-6 animate-fade-in">
            <div>
              <h2 className="text-2xl font-bold mb-2 text-white">{t(lang, 'eventDetails')}</h2>
              <p className="text-zinc-500 text-sm">{t(lang, 'step1Desc')}</p>
            </div>

            {/* Templates */}
            <div>
              <label className="block text-sm font-medium mb-3 text-zinc-200">{t(lang, 'templates') || 'Quick Start Templates'}</label>
              <div className="grid grid-cols-2 gap-3">
                {templates.map((tmpl) => (
                  <button
                    key={tmpl.id}
                    onClick={() => applyTemplate(tmpl)}
                    className="flex flex-col items-start gap-2 p-4 rounded-xl border border-zinc-800 bg-zinc-900/30 hover:border-zinc-600 hover:bg-zinc-800/50 transition-colors text-start"
                  >
                    <span className="text-2xl">{tmpl.emoji}</span>
                    <span className="text-sm font-medium text-white">{tmpl.name}</span>
                    <span className="text-xs text-zinc-500 line-clamp-2">{tmpl.description}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2 text-zinc-200">{t(lang, 'eventName')} *</label>
                <input
                  type="text"
                  placeholder={t(lang, 'eventNamePlaceholder')}
                  value={form.name}
                  onChange={(e) => updateForm('name', e.target.value)}
                  className="w-full h-12 px-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-600 transition-colors"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-2 text-zinc-200">{t(lang, 'description')}</label>
                <textarea
                  placeholder={t(lang, 'descriptionPlaceholder')}
                  value={form.description}
                  onChange={(e) => updateForm('description', e.target.value)}
                  rows={3}
                  className="w-full px-4 py-3 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-600 transition-colors resize-none"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-3 text-zinc-200">{t(lang, 'type')}</label>
                <div className="grid grid-cols-3 gap-2">
                  {eventTypes.map((type) => (
                    <button
                      key={type.id}
                      onClick={() => updateForm('eventType', type.id)}
                      className={`flex flex-col items-center gap-1.5 p-3 rounded-xl border transition-colors ${
                        form.eventType === type.id
                          ? 'border-white bg-zinc-800'
                          : 'border-zinc-800 bg-zinc-900/30 hover:border-zinc-700'
                      }`}
                    >
                      <span className="text-2xl">{type.emoji}</span>
                      <span className="text-xs text-zinc-400">{type.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="space-y-6 animate-fade-in">
            <div>
              <h2 className="text-2xl font-bold mb-2 text-white">{t(lang, 'dateTime')}</h2>
              <p className="text-zinc-500 text-sm">{t(lang, 'step2Desc') || 'When does your event happen?'}</p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2">{t(lang, 'startDate')} *</label>
                <input
                  type="datetime-local"
                  value={form.startDate}
                  onChange={(e) => updateForm('startDate', e.target.value)}
                  className="w-full h-12 px-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white focus:outline-none focus:border-zinc-600 transition-colors"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">{t(lang, 'endDate')}</label>
                <input
                  type="datetime-local"
                  value={form.endDate}
                  onChange={(e) => updateForm('endDate', e.target.value)}
                  className="w-full h-12 px-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white focus:outline-none focus:border-zinc-600 transition-colors"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">{t(lang, 'albumRevealDate')}</label>
                <input
                  type="datetime-local"
                  value={form.revealDate}
                  onChange={(e) => updateForm('revealDate', e.target.value)}
                  className="w-full h-12 px-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white focus:outline-none focus:border-zinc-600 transition-colors"
                />
                <p className="text-xs text-zinc-500 mt-1">{t(lang, 'albumRevealDateDesc')}</p>
              </div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="space-y-6 animate-fade-in">
            <div>
              <h2 className="text-2xl font-bold mb-2 text-white">{t(lang, 'privacyPermissions')}</h2>
              <p className="text-zinc-500 text-sm">{t(lang, 'step3Desc') || 'Control who can see and share photos.'}</p>
            </div>

            <div className="space-y-4">
              {/* Max Photos */}
              <div>
                <label className="block text-sm font-medium mb-2">
                  {t(lang, 'maxPhotosPerGuest')}: {form.maxPhotosPerGuest}
                </label>
                <input
                  type="range"
                  min={1}
                  max={50}
                  value={form.maxPhotosPerGuest}
                  onChange={(e) => updateForm('maxPhotosPerGuest', parseInt(e.target.value))}
                  className="w-full accent-white"
                />
              </div>

              {/* Max Guests */}
              <div>
                <label className="block text-sm font-medium mb-2">
                  {t(lang, 'maxGuests') || 'Max Guests'}: {form.maxGuests}
                </label>
                <input
                  type="range"
                  min={5}
                  max={200}
                  step={5}
                  value={form.maxGuests}
                  onChange={(e) => updateForm('maxGuests', parseInt(e.target.value))}
                  className="w-full accent-white"
                />
                <p className="text-xs text-zinc-500 mt-1">{t(lang, 'maxGuestsDesc') || 'Guests beyond this limit will need an upgrade.'}</p>
              </div>

              {/* Watermark Text */}
              <div>
                <label className="block text-sm font-medium mb-2">
                  {t(lang, 'watermarkText') || 'Watermark Text'}
                </label>
                <input
                  type="text"
                  value={form.watermarkText}
                  onChange={(e) => updateForm('watermarkText', e.target.value)}
                  placeholder="Momira — momira.app"
                  className="w-full h-10 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-500"
                />
                <p className="text-xs text-zinc-500 mt-1">{t(lang, 'watermarkDesc') || 'Text to overlay on downloaded photos.'}</p>
              </div>

              {/* Toggle Switches */}
              {[
                { key: 'isPrivate', label: t(lang, 'privateEvent'), desc: t(lang, 'step1Desc'), icon: Lock },
                { key: 'requireHostApproval', label: t(lang, 'requireHostApproval'), desc: t(lang, 'step2Desc'), icon: Check },
                { key: 'allowGuestSharing', label: t(lang, 'allowGuestSharing'), desc: t(lang, 'step3Desc'), icon: Unlock },
                { key: 'autoApproveTrustedGuests', label: t(lang, 'autoApproveTrustedGuests'), desc: t(lang, 'autoApproveTrustedGuests'), icon: Users },
                { key: 'allowCoHost', label: t(lang, 'allowCoHost'), desc: t(lang, 'allowCoHostDesc'), icon: Users },
              ].map((toggle) => (
                <div
                  key={toggle.key}
                  className="flex items-center justify-between p-4 rounded-xl border border-zinc-800 bg-zinc-900/30"
                >
                  <div className="flex items-center gap-3">
                    <toggle.icon className="h-5 w-5 text-zinc-400" />
                    <div>
                      <div className="text-sm font-medium text-zinc-200">{toggle.label}</div>
                      <div className="text-xs text-zinc-500">{toggle.desc}</div>
                    </div>
                  </div>
                  <button
                    onClick={() => updateForm(toggle.key, !form[toggle.key as keyof typeof form])}
                    className={`relative h-7 w-12 rounded-full transition-colors ${
                      form[toggle.key as keyof typeof form] ? 'bg-white' : 'bg-zinc-700'
                    }`}
                  >
                    <div
                      className={`absolute top-0.5 h-6 w-6 rounded-full bg-black transition-transform ${
                        form[toggle.key as keyof typeof form] ? 'translate-x-[22px]' : 'translate-x-0.5'
                      }`}
                    />
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Navigation */}
        <div className="flex items-center gap-3 mt-8">
          {step > 1 && (
            <button
              onClick={() => setStep(step - 1)}
              className="h-12 px-6 rounded-xl border border-zinc-800 text-zinc-300 font-medium hover:bg-zinc-900 transition-colors"
            >
              {t(lang, 'back')}
            </button>
          )}
          {step < 3 ? (
            <button
              onClick={() => setStep(step + 1)}
              className="flex-1 h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium hover:from-indigo-600 hover:to-purple-700 transition-all shadow-md shadow-indigo-500/20"
            >
              {t(lang, 'continue')}
            </button>
          ) : (
            <button
              onClick={handleCreate}
              disabled={loading}
              className="flex-1 h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium hover:from-indigo-600 hover:to-purple-700 transition-all shadow-md shadow-indigo-500/20 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              <Camera className="h-5 w-5" />
              {loading ? t(lang, 'creating') : t(lang, 'createEvent')}
            </button>
          )}
        </div>
      </main>
    </div>
  );
}
