import { useState } from 'react'
import { Button } from '@/components/ui/Button'
import { Card } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'
import {
  CheckCircle2,
  ArrowRight,
  ArrowLeft,
  Building2,
  Users,
  Settings,
  Sparkles,
  Briefcase,
} from 'lucide-react'

interface OnboardingStep {
  id: string
  title: string
  description: string
  icon: React.ElementType
  component: React.ReactNode
}

interface OnboardingModalProps {
  isOpen: boolean
  onComplete: () => void
  tenantName?: string
}

export function OnboardingModal({ isOpen, onComplete, tenantName = 'din verksamhet' }: OnboardingModalProps) {
  const [currentStep, setCurrentStep] = useState(0)
  const [completedSteps, setCompletedSteps] = useState<string[]>([])

  const steps: OnboardingStep[] = [
    {
      id: 'welcome',
      title: 'Välkommen till BOC',
      description: `Låt oss konfigurera ${tenantName}`,
      icon: Sparkles,
      component: <WelcomeStep tenantName={tenantName} />,
    },
    {
      id: 'company',
      title: 'Företagsinformation',
      description: 'Grundläggande uppgifter om verksamheten',
      icon: Building2,
      component: <CompanyStep />,
    },
    {
      id: 'users',
      title: 'Lägg till användare',
      description: 'Bjud in teammedlemmar',
      icon: Users,
      component: <UsersStep />,
    },
    {
      id: 'settings',
      title: 'Inställningar',
      description: 'Konfigurera bokföring och moms',
      icon: Settings,
      component: <SettingsStep />,
    },
    {
      id: 'complete',
      title: 'Klart!',
      description: 'Du är redo att börja',
      icon: CheckCircle2,
      component: <CompleteStep onComplete={onComplete} />,
    },
  ]

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCompletedSteps([...completedSteps, steps[currentStep].id])
      setCurrentStep(currentStep + 1)
    }
  }

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

  const handleSkip = () => {
    onComplete()
  }

  if (!isOpen) return null

  const step = steps[currentStep]
  const isLastStep = currentStep === steps.length - 1
  const isFirstStep = currentStep === 0

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-2xl mx-4">
        <Card className="overflow-hidden">
          {/* Progress Header */}
          <div className="bg-gradient-to-r from-primary to-primary-hover p-6 text-white">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <step.icon size={24} />
                <span className="text-sm font-medium">Steg {currentStep + 1} av {steps.length}</span>
              </div>
              {!isLastStep && (
                <button onClick={handleSkip} className="text-sm text-white/80 hover:text-white">
                  Hoppa över
                </button>
              )}
            </div>
            <h2 className="text-2xl font-bold mb-1">{step.title}</h2>
            <p className="text-white/80">{step.description}</p>

            {/* Progress Bar */}
            <div className="flex items-center gap-2 mt-6">
              {steps.map((s, i) => (
                <div key={s.id} className="flex-1 flex items-center gap-2">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${
                    i <= currentStep ? 'bg-white text-primary' : 'bg-white/20 text-white/60'
                  }`}>
                    {completedSteps.includes(s.id) ? (
                      <CheckCircle2 size={16} />
                    ) : (
                      i + 1
                    )}
                  </div>
                  {i < steps.length - 1 && (
                    <div className={`flex-1 h-1 rounded-full transition-colors ${
                      i < currentStep ? 'bg-white' : 'bg-white/20'
                    }`} />
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Step Content */}
          <div className="p-6 min-h-[300px]">
            {step.component}
          </div>

          {/* Footer */}
          <div className="p-6 border-t border-border flex items-center justify-between">
            <Button
              variant="secondary"
              onClick={handleBack}
              disabled={isFirstStep}
              icon={<ArrowLeft size={16} />}
            >
              Tillbaka
            </Button>

            {isLastStep ? (
              <Button onClick={onComplete} icon={<Sparkles size={16} />}>
                Kom igång
              </Button>
            ) : (
              <Button onClick={handleNext} icon={<ArrowRight size={16} />}>
                Nästa steg
              </Button>
            )}
          </div>
        </Card>
      </div>
    </div>
  )
}

function WelcomeStep({ tenantName }: { tenantName: string }) {
  return (
    <div className="text-center space-y-4">
      <div className="w-20 h-20 rounded-2xl bg-primary/10 flex items-center justify-center mx-auto">
        <Sparkles size={40} className="text-primary" />
      </div>
      <h3 className="text-xl font-semibold">Välkommen till Business Operations Center</h3>
      <p className="text-text-secondary">
        BOC är ditt kompletta affärssystem för att hantera {tenantName}. 
        Vi ska gå igenom några snabba steg för att komma igång.
      </p>
      <div className="grid grid-cols-2 gap-4 mt-6">
        {[
          { icon: Building2, label: 'Företagsinfo', desc: 'Organisationsnummer, adress' },
          { icon: Users, label: 'Team', desc: 'Bjud in kollegor' },
          { icon: Briefcase, label: 'Bokföring', desc: 'BAS-kontoplan, moms' },
          { icon: Settings, label: 'Inställningar', desc: 'Valuta, språk' },
        ].map((item) => (
          <div key={item.label} className="p-4 rounded-xl bg-surface border border-border">
            <item.icon size={24} className="text-primary mb-2" />
            <p className="font-medium text-sm">{item.label}</p>
            <p className="text-xs text-text-secondary">{item.desc}</p>
          </div>
        ))}
      </div>
    </div>
  )
}

function CompanyStep() {
  const [formData, setFormData] = useState({
    orgNumber: '',
    companyName: 'Landvex AB',
    address: '',
    city: '',
    postalCode: '',
    vatNumber: '',
  })

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Företagsnamn</label>
          <input
            type="text"
            value={formData.companyName}
            onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
            className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Organisationsnummer</label>
          <input
            type="text"
            placeholder="559141-7042"
            value={formData.orgNumber}
            onChange={(e) => setFormData({ ...formData, orgNumber: e.target.value })}
            className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Adress</label>
        <input
          type="text"
          value={formData.address}
          onChange={(e) => setFormData({ ...formData, address: e.target.value })}
          className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
        />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Postnummer</label>
          <input
            type="text"
            value={formData.postalCode}
            onChange={(e) => setFormData({ ...formData, postalCode: e.target.value })}
            className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Ort</label>
          <input
            type="text"
            value={formData.city}
            onChange={(e) => setFormData({ ...formData, city: e.target.value })}
            className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Momsregistreringsnummer</label>
        <input
          type="text"
          placeholder="SE559141704201"
          value={formData.vatNumber}
          onChange={(e) => setFormData({ ...formData, vatNumber: e.target.value })}
          className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
        />
      </div>
    </div>
  )
}

function UsersStep() {
  const [emails, setEmails] = useState([''])

  const addEmail = () => setEmails([...emails, ''])
  const updateEmail = (index: number, value: string) => {
    const newEmails = [...emails]
    newEmails[index] = value
    setEmails(newEmails)
  }

  return (
    <div className="space-y-4">
      <p className="text-text-secondary">Bjud in dina teammedlemmar via e-post. De får en inbjudan att gå med i verksamheten.</p>
      
      {emails.map((email, index) => (
        <div key={index} className="flex items-center gap-2">
          <input
            type="email"
            placeholder="namn@foretag.se"
            value={email}
            onChange={(e) => updateEmail(index, e.target.value)}
            className="flex-1 h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
          <select className="h-10 px-3 rounded-[14px] border bg-surface text-sm">
            <option value="admin">Admin</option>
            <option value="manager">Manager</option>
            <option value="user">Användare</option>
          </select>
        </div>
      ))}

      <Button variant="secondary" onClick={addEmail} className="w-full">
        + Lägg till fler
      </Button>

      <div className="p-4 bg-primary/5 rounded-xl border border-primary/20">
        <p className="text-sm font-medium text-primary">💡 Tips</p>
        <p className="text-xs text-text-secondary mt-1">
          Du kan alltid bjuda in fler användare senare från HR-modulen.
        </p>
      </div>
    </div>
  )
}

function SettingsStep() {
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Valuta</label>
          <select className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm">
            <option value="SEK">SEK (Svenska kronor)</option>
            <option value="EUR">EUR (Euro)</option>
            <option value="USD">USD (US Dollar)</option>
            <option value="NOK">NOK (Norska kronor)</option>
            <option value="DKK">DKK (Danska kronor)</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Bokföringsstandard</label>
          <select className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm">
            <option value="BAS2024">BAS 2024 (Sverige)</option>
            <option value="BAS2023">BAS 2023 (Sverige)</option>
            <option value="EU">EU-standard</option>
          </select>
        </div>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Momssats (%)</label>
          <input
            type="number"
            defaultValue={25}
            className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Räkenskapsår start</label>
          <input
            type="date"
            defaultValue="2026-01-01"
            className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
          />
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Språk</label>
        <select className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm">
          <option value="sv">Svenska</option>
          <option value="en">English</option>
          <option value="no">Norsk</option>
          <option value="da">Dansk</option>
        </select>
      </div>
      <div className="p-4 bg-warning/5 rounded-xl border border-warning/20">
        <p className="text-sm font-medium text-warning">⚠️ Viktigt</p>
        <p className="text-xs text-text-secondary mt-1">
          Dessa inställningar påverkar hela verksamhetens bokföring. Kontrollera med din revisor om du är osäker.
        </p>
      </div>
    </div>
  )
}

function CompleteStep({ onComplete: _onComplete }: { onComplete: () => void }) {
  return (
    <div className="text-center space-y-4">
      <div className="w-20 h-20 rounded-full bg-success/10 flex items-center justify-center mx-auto">
        <CheckCircle2 size={40} className="text-success" />
      </div>
      <h3 className="text-xl font-semibold">Allt är klart!</h3>
      <p className="text-text-secondary">
        Din verksamhet är nu konfigurerad och du är redo att börja använda BOC.
      </p>
      <div className="grid grid-cols-3 gap-4 mt-6">
        {[
          { label: 'Företag', status: 'Klart' },
          { label: 'Team', status: 'Klart' },
          { label: 'Inställningar', status: 'Klart' },
        ].map((item) => (
          <div key={item.label} className="p-3 rounded-xl bg-surface border border-border">
            <Badge variant="success" className="mb-2">{item.status}</Badge>
            <p className="text-sm font-medium">{item.label}</p>
          </div>
        ))}
      </div>
    </div>
  )
}
