'use client';

import { useState } from 'react';
import { Building2, GitBranch, BookOpen, Bot, Check, ChevronRight, ChevronLeft } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import Icon from '@client/components/ui/AppIcon';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePublicBranding } from '@client/hooks/usePublicBranding';

export default function OnboardingPage() {
  const { t } = useLanguage();
  const { logoUrl, siteTitle } = usePublicBranding();
  const [currentStep, setCurrentStep] = useState(1);
  const [form, setForm] = useState({
    restaurantName: '',
    cuisine: '',
    phone: '',
    website: '',
    branchName: '',
    address: '',
    timezone: 'America/Los_Angeles',
    openTime: '09:00',
    closeTime: '22:00',
    agentName: 'Alex',
    agentStyle: 'friendly',
    voiceEnabled: true,
    chatEnabled: true,
  });

  const steps = [
    { id: 1, title: t('onboarding.step1.title', 'Restaurant Profile'), icon: Building2, desc: t('onboarding.step1.desc', 'Tell us about your restaurant') },
    { id: 2, title: t('onboarding.step2.title', 'Branch Setup'), icon: GitBranch, desc: t('onboarding.step2.desc', 'Set up your first location') },
    { id: 3, title: t('onboarding.step3.title', 'Menu Intro'), icon: BookOpen, desc: t('onboarding.step3.desc', 'Add your first menu items') },
    { id: 4, title: t('onboarding.step4.title', 'AI Agent'), icon: Bot, desc: t('onboarding.step4.desc', 'Configure your AI assistant') },
  ];

  const progress = ((currentStep - 1) / (steps.length - 1)) * 100;

  const handleNext = () => {
    if (currentStep < steps.length) setCurrentStep(s => s + 1);
    else window.location.href = '/restaurant-dashboard';
  };

  const handleBack = () => {
    if (currentStep > 1) setCurrentStep(s => s - 1);
  };

  return (
    <div className="min-h-screen flex" style={{ backgroundColor: 'hsl(var(--background))' }}>
      {/* Left sidebar */}
      <div className="hidden lg:flex lg:w-72 flex-col p-8" style={{ backgroundColor: 'hsl(var(--surface))', borderRight: '1px solid hsl(var(--border))' }}>
        <div className="flex items-center gap-2 mb-10">
          <AppLogo src={logoUrl || undefined} size={28} />
          <span className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{siteTitle}</span>
        </div>

        <div className="space-y-2">
          {steps.map(step => {
            const StepIcon = step.icon;
            const isCompleted = step.id < currentStep;
            const isActive = step.id === currentStep;
            return (
              <div
                key={step.id}
                className="flex items-center gap-3 p-3 rounded-xl transition-all"
                style={{ backgroundColor: isActive ? 'hsl(var(--primary-light))' : 'transparent' }}
              >
                <div
                  className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0"
                  style={{
                    backgroundColor: isCompleted ? 'hsl(var(--success))' : isActive ? 'hsl(var(--primary))' : 'hsl(var(--muted))',
                  }}
                >
                  {isCompleted ? (
                    <Check size={16} className="text-white" />
                  ) : (
                    <StepIcon size={16} style={{ color: isActive ? 'white' : 'hsl(var(--muted-foreground))' }} />
                  )}
                </div>
                <div>
                  <p className="text-sm font-semibold" style={{ color: isActive ? 'hsl(var(--primary))' : 'hsl(var(--foreground))' }}>{step.title}</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{step.desc}</p>
                </div>
              </div>
            );
          })}
        </div>

        <div className="mt-auto">
          <div className="h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            <div className="h-full rounded-full transition-all duration-500" style={{ width: `${progress}%`, backgroundColor: 'hsl(var(--primary))' }} />
          </div>
          <p className="text-xs mt-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.stepOf', 'Step {{current}} of {{total}}', { current: currentStep, total: steps.length })}</p>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 flex items-center justify-center p-6 lg:p-12">
        <div className="w-full max-w-lg">
          {/* Mobile progress */}
          <div className="lg:hidden mb-6">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{steps[currentStep - 1].title}</span>
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{currentStep}/{steps.length}</span>
            </div>
            <div className="h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              <div className="h-full rounded-full transition-all" style={{ width: `${(currentStep / steps.length) * 100}%`, backgroundColor: 'hsl(var(--primary))' }} />
            </div>
          </div>

          {/* Step 1: Restaurant Profile */}
          {currentStep === 1 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step1.title', 'Restaurant Profile')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step1.subtitle', 'Basic information about your restaurant')}</p>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.restaurantName', 'Restaurant Name')} *</label>
                  <input className="input-base" placeholder={t('onboarding.restaurantNamePlaceholder', 'The Rustic Fork')} value={form.restaurantName} onChange={e => setForm({ ...form, restaurantName: e.target.value })} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.cuisineType', 'Cuisine Type')}</label>
                  <select className="input-base" value={form.cuisine} onChange={e => setForm({ ...form, cuisine: e.target.value })}>
                    <option value="">{t('onboarding.selectCuisine', 'Select cuisine type')}</option>
                    <option value="Italian">{t('onboarding.cuisine.italian', 'Italian')}</option>
                    <option value="American">{t('onboarding.cuisine.american', 'American')}</option>
                    <option value="Asian Fusion">{t('onboarding.cuisine.asianFusion', 'Asian Fusion')}</option>
                    <option value="Mexican">{t('onboarding.cuisine.mexican', 'Mexican')}</option>
                    <option value="Mediterranean">{t('onboarding.cuisine.mediterranean', 'Mediterranean')}</option>
                    <option value="Other">{t('onboarding.cuisine.other', 'Other')}</option>
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.phoneNumber', 'Phone Number')}</label>
                    <input className="input-base" placeholder={t('onboarding.phonePlaceholder', '+1 (555) 000-0000')} value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.website', 'Website (optional)')}</label>
                    <input className="input-base" placeholder={t('onboarding.websitePlaceholder', 'www.yourrestaurant.com')} value={form.website} onChange={e => setForm({ ...form, website: e.target.value })} />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 2: Branch Setup */}
          {currentStep === 2 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step2.heading', 'First Branch Setup')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step2.subtitle', 'Set up your primary location')}</p>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.branchName', 'Branch Name')}</label>
                  <input className="input-base" placeholder={t('onboarding.branchNamePlaceholder', 'Main Branch / Downtown')} value={form.branchName} onChange={e => setForm({ ...form, branchName: e.target.value })} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.address', 'Address')}</label>
                  <input className="input-base" placeholder={t('onboarding.addressPlaceholder', '123 Main Street, City, State')} value={form.address} onChange={e => setForm({ ...form, address: e.target.value })} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.timezone', 'Timezone')}</label>
                  <select className="input-base" value={form.timezone} onChange={e => setForm({ ...form, timezone: e.target.value })}>
                    <option value="America/Los_Angeles">{t('onboarding.tz.pacific', 'Pacific Time (PT)')}</option>
                    <option value="America/Denver">{t('onboarding.tz.mountain', 'Mountain Time (MT)')}</option>
                    <option value="America/Chicago">{t('onboarding.tz.central', 'Central Time (CT)')}</option>
                    <option value="America/New_York">{t('onboarding.tz.eastern', 'Eastern Time (ET)')}</option>
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.openingTime', 'Opening Time')}</label>
                    <input type="time" className="input-base" value={form.openTime} onChange={e => setForm({ ...form, openTime: e.target.value })} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.closingTime', 'Closing Time')}</label>
                    <input type="time" className="input-base" value={form.closeTime} onChange={e => setForm({ ...form, closeTime: e.target.value })} />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Menu Intro */}
          {currentStep === 3 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step3.heading', 'Menu Setup')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step3.subtitle', 'Choose how you want to add your menu')}</p>
              <div className="space-y-3">
                {[
                  { id: 'manual', title: t('onboarding.menu.manual', 'Add manually'), desc: t('onboarding.menu.manualDesc', 'Enter items one by one using our menu editor'), icon: '✏️' },
                  { id: 'bulk', title: t('onboarding.menu.bulk', 'Bulk upload with AI'), desc: t('onboarding.menu.bulkDesc', 'Upload a PDF, image, or CSV — AI will extract items automatically'), icon: '🤖', recommended: true },
                  { id: 'later', title: t('onboarding.menu.later', 'Skip for now'), desc: t('onboarding.menu.laterDesc', 'Set up your menu later from Menu Management'), icon: '⏭️' },
                ].map(opt => (
                  <div
                    key={opt.id}
                    className="flex items-start gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all"
                    style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--surface))' }}
                    onClick={() => opt.id !== 'later' ? window.location.href = '/menu-management' : undefined}
                  >
                    <span className="text-2xl">{opt.icon}</span>
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{opt.title}</p>
                        {opt.recommended && <span className="badge badge-primary text-xs">{t('common.recommended', 'Recommended')}</span>}
                      </div>
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{opt.desc}</p>
                    </div>
                    <ChevronRight size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Step 4: AI Agent */}
          {currentStep === 4 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step4.heading', 'Configure AI Agent')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step4.subtitle', 'Personalize your AI assistant')}</p>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.agentName', 'Agent Name')}</label>
                  <input className="input-base" placeholder={t('onboarding.agentNamePlaceholder', 'Alex')} value={form.agentName} onChange={e => setForm({ ...form, agentName: e.target.value })} />
                  <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.agentNameHint', 'Customers will see this name in conversations')}</p>
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.conversationStyle', 'Conversation Style')}</label>
                  <div className="grid grid-cols-3 gap-2">
                    {[
                      { id: 'friendly', label: t('onboarding.style.friendly', 'Friendly') },
                      { id: 'professional', label: t('onboarding.style.professional', 'Professional') },
                      { id: 'concise', label: t('onboarding.style.concise', 'Concise') },
                    ].map(style => (
                      <button
                        key={style.id}
                        type="button"
                        onClick={() => setForm({ ...form, agentStyle: style.id })}
                        className="py-2 px-3 rounded-lg border-2 text-sm font-medium transition-all"
                        style={{
                          borderColor: form.agentStyle === style.id ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                          backgroundColor: form.agentStyle === style.id ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                          color: form.agentStyle === style.id ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))',
                        }}
                      >
                        {style.label}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="card p-4 space-y-3">
                  <p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.enableChannels', 'Enable Channels')}</p>
                  {[
                    { key: 'voiceEnabled', label: t('onboarding.channel.voice', 'Voice Agent'), desc: t('onboarding.channel.voiceDesc', 'Handle inbound phone calls') },
                    { key: 'chatEnabled', label: t('onboarding.channel.chat', 'Chat Agent'), desc: t('onboarding.channel.chatDesc', 'Web chat & messaging apps') },
                  ].map(ch => (
                    <div key={ch.key} className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{ch.label}</p>
                        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{ch.desc}</p>
                      </div>
                      <button
                        type="button"
                        onClick={() => setForm({ ...form, [ch.key]: !form[ch.key as keyof typeof form] })}
                        className="w-10 h-6 rounded-full transition-all relative"
                        style={{ backgroundColor: form[ch.key as keyof typeof form] ? 'hsl(var(--primary))' : 'hsl(var(--muted))' }}
                      >
                        <span
                          className="absolute top-1 w-4 h-4 bg-white rounded-full shadow transition-all"
                          style={{ left: form[ch.key as keyof typeof form] ? '22px' : '2px' }}
                        />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Navigation */}
          <div className="flex items-center justify-between mt-8">
            <button
              onClick={handleBack}
              disabled={currentStep === 1}
              className="btn-secondary disabled:opacity-40"
            >
              <ChevronLeft size={16} /> {t('common.back', 'Back')}
            </button>
            <button onClick={handleNext} className="btn-primary">
              {currentStep === steps.length ? (
                <>{t('onboarding.goToDashboard', 'Go to Dashboard')} <ChevronRight size={16} /></>
              ) : (
                <>{t('common.continue', 'Continue')} <ChevronRight size={16} /></>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
