import { useState, useEffect } from 'react'
import { Card, CardHeader } from '@/components/ui/Card'
import { Button } from '@/components/ui/Button'
import { Skeleton } from '@/components/ui/Skeleton'
import { Badge } from '@/components/ui/Badge'
import { useAuthStore } from '@/stores/authStore'
import { formatDate } from '@/lib/utils'
import {
  User,
  Mail,
  Phone,
  Building2,
  Shield,
  Bell,
  Moon,
  Globe,
  Key,
  Camera,
  Save,
  Sun,
  Monitor,
} from 'lucide-react'

interface UserProfile {
  id: string
  name: string
  email: string
  phone?: string
  avatar?: string
  role: string
  department?: string
  timezone: string
  language: string
  notifications: {
    email: boolean
    push: boolean
    sms: boolean
  }
  theme: 'light' | 'dark' | 'system'
  twoFactorEnabled: boolean
  lastLogin: string
  createdAt: string
}

export function ProfilePage() {
  const { user } = useAuthStore()
  const [profile, setProfile] = useState<UserProfile | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [activeTab, setActiveTab] = useState('general')

  useEffect(() => {
    // Mock data - skulle hämtas från API
    setTimeout(() => {
      setProfile({
        id: user?.id || '3847477b-3d56-4975-9157-ae8f9ce52aa7',
        name: user?.name || 'Erik Svensson',
        email: user?.email || 'erik@landvex.com',
        phone: '+46 70 123 45 67',
        role: user?.role || 'admin',
        department: 'Ledning',
        timezone: 'Europe/Stockholm',
        language: 'sv',
        notifications: {
          email: true,
          push: true,
          sms: false,
        },
        theme: 'light',
        twoFactorEnabled: false,
        lastLogin: new Date().toISOString(),
        createdAt: '2026-01-15T10:30:00Z',
      })
      setLoading(false)
    }, 500)
  }, [user])

  const handleSave = async () => {
    setSaving(true)
    // TODO: API call to save profile
    await new Promise(resolve => setTimeout(resolve, 1000))
    setSaving(false)
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-[200px]" />
        <Skeleton className="h-[400px]" />
      </div>
    )
  }

  if (!profile) return null

  const tabs = [
    { id: 'general', label: 'Allmänt', icon: User },
    { id: 'security', label: 'Säkerhet', icon: Shield },
    { id: 'notifications', label: 'Notifikationer', icon: Bell },
    { id: 'preferences', label: 'Inställningar', icon: Globe },
  ]

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Min Profil</h1>
          <p className="text-text-secondary">Hantera dina kontoinställningar</p>
        </div>
        <Button
          onClick={handleSave}
          disabled={saving}
          icon={saving ? undefined : <Save size={16} />}
        >
          {saving ? 'Sparar...' : 'Spara ändringar'}
        </Button>
      </div>

      {/* Profile Header Card */}
      <Card className="relative overflow-hidden">
        <div className="h-32 bg-gradient-to-r from-primary to-primary-hover" />
        <div className="px-6 pb-6">
          <div className="relative -mt-16 mb-4">
            <div className="w-32 h-32 rounded-2xl bg-surface border-4 border-bg flex items-center justify-center text-4xl font-bold text-primary relative">
              {profile.avatar ? (
                <img src={profile.avatar} alt={profile.name} className="w-full h-full rounded-2xl object-cover" />
              ) : (
                profile.name.split(' ').map(n => n[0]).join('')
              )}
              <button className="absolute bottom-0 right-0 w-8 h-8 bg-primary text-white rounded-full flex items-center justify-center hover:bg-primary-hover transition-colors">
                <Camera size={14} />
              </button>
            </div>
          </div>
          <div className="flex items-start justify-between">
            <div>
              <h2 className="text-xl font-semibold">{profile.name}</h2>
              <p className="text-text-secondary">{profile.email}</p>
              <div className="flex items-center gap-2 mt-2">
                <Badge variant="primary">{profile.role}</Badge>
                <Badge variant="default">{profile.department}</Badge>
              </div>
            </div>
            <div className="text-right text-sm text-text-secondary">
              <p>Senaste inloggning: {formatDate(profile.lastLogin)}</p>
              <p>Medlem sedan: {formatDate(profile.createdAt)}</p>
            </div>
          </div>
        </div>
      </Card>

      {/* Tabs */}
      <div className="flex items-center gap-1 bg-bg rounded-xl p-1 overflow-x-auto">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors whitespace-nowrap flex items-center gap-2 ${
              activeTab === tab.id
                ? 'bg-surface text-text-primary shadow-sm'
                : 'text-text-secondary hover:text-text-primary'
            }`}
          >
            <tab.icon size={16} />
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      {activeTab === 'general' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card>
            <CardHeader title="Personlig information" subtitle="Uppdatera dina kontouppgifter" />
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Fullständigt namn</label>
                <div className="relative">
                  <User size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
                  <input
                    type="text"
                    value={profile.name}
                    onChange={(e) => setProfile({ ...profile, name: e.target.value })}
                    className="w-full h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">E-post</label>
                <div className="relative">
                  <Mail size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
                  <input
                    type="email"
                    value={profile.email}
                    onChange={(e) => setProfile({ ...profile, email: e.target.value })}
                    className="w-full h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Telefon</label>
                <div className="relative">
                  <Phone size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
                  <input
                    type="tel"
                    value={profile.phone || ''}
                    onChange={(e) => setProfile({ ...profile, phone: e.target.value })}
                    className="w-full h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Avdelning</label>
                <div className="relative">
                  <Building2 size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
                  <input
                    type="text"
                    value={profile.department || ''}
                    onChange={(e) => setProfile({ ...profile, department: e.target.value })}
                    className="w-full h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm"
                  />
                </div>
              </div>
            </div>
          </Card>

          <Card>
            <CardHeader title="Kontoinformation" subtitle="Dina kontodetaljer" />
            <div className="p-4 space-y-4">
              <div className="flex items-center justify-between py-3 border-b border-border">
                <div>
                  <p className="text-sm font-medium">Användar-ID</p>
                  <p className="text-xs text-text-secondary">{profile.id}</p>
                </div>
                <Badge variant="default">Aktiv</Badge>
              </div>
              <div className="flex items-center justify-between py-3 border-b border-border">
                <div>
                  <p className="text-sm font-medium">Roll</p>
                  <p className="text-xs text-text-secondary">{profile.role}</p>
                </div>
                <Shield size={16} className="text-primary" />
              </div>
              <div className="flex items-center justify-between py-3 border-b border-border">
                <div>
                  <p className="text-sm font-medium">Tidszon</p>
                  <p className="text-xs text-text-secondary">{profile.timezone}</p>
                </div>
                <Globe size={16} className="text-text-secondary" />
              </div>
              <div className="flex items-center justify-between py-3">
                <div>
                  <p className="text-sm font-medium">Språk</p>
                  <p className="text-xs text-text-secondary">{profile.language === 'sv' ? 'Svenska' : profile.language}</p>
                </div>
                <Globe size={16} className="text-text-secondary" />
              </div>
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'security' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card>
            <CardHeader title="Lösenord" subtitle="Uppdatera ditt lösenord" />
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Nuvarande lösenord</label>
                <div className="relative">
                  <Key size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
                  <input
                    type="password"
                    placeholder="••••••••"
                    className="w-full h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Nytt lösenord</label>
                <input
                  type="password"
                  placeholder="Minst 8 tecken"
                  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">Bekräfta nytt lösenord</label>
                <input
                  type="password"
                  placeholder="Upprepa lösenord"
                  className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
                />
              </div>
              <Button variant="secondary" className="w-full">
                <Key size={16} className="mr-2" />
                Ändra lösenord
              </Button>
            </div>
          </Card>

          <Card>
            <CardHeader title="Tvåfaktorsautentisering" subtitle="Öka säkerheten på ditt konto" />
            <div className="p-4">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <p className="text-sm font-medium">2FA-status</p>
                  <p className="text-xs text-text-secondary">
                    {profile.twoFactorEnabled ? 'Aktiverad' : 'Ej aktiverad'}
                  </p>
                </div>
                <Badge variant={profile.twoFactorEnabled ? 'success' : 'default'}>
                  {profile.twoFactorEnabled ? 'Aktiv' : 'Inaktiv'}
                </Badge>
              </div>
              {!profile.twoFactorEnabled && (
                <Button className="w-full">
                  <Shield size={16} className="mr-2" />
                  Aktivera 2FA
                </Button>
              )}
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'notifications' && (
        <Card>
          <CardHeader title="Notifikationsinställningar" subtitle="Hantera hur du får notifieringar" />
          <div className="p-4 space-y-4">
            {[
              { key: 'email', label: 'E-postnotifikationer', description: 'Få uppdateringar via e-post', icon: Mail },
              { key: 'push', label: 'Push-notifikationer', description: 'Få notifikationer i webbläsaren', icon: Bell },
              { key: 'sms', label: 'SMS-notifikationer', description: 'Få viktiga uppdateringar via SMS', icon: Phone },
            ].map((item) => (
              <div key={item.key} className="flex items-center justify-between py-3 border-b border-border last:border-0">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <item.icon size={18} />
                  </div>
                  <div>
                    <p className="text-sm font-medium">{item.label}</p>
                    <p className="text-xs text-text-secondary">{item.description}</p>
                  </div>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={profile.notifications[item.key as keyof typeof profile.notifications]}
                    onChange={(e) => setProfile({
                      ...profile,
                      notifications: {
                        ...profile.notifications,
                        [item.key]: e.target.checked,
                      },
                    })}
                    className="sr-only peer"
                  />
                  <div className="w-11 h-6 bg-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary" />
                </label>
              </div>
            ))}
          </div>
        </Card>
      )}

      {activeTab === 'preferences' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card>
            <CardHeader title="Utseende" subtitle="Anpassa hur BOC ser ut" />
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2">Tema</label>
                <div className="grid grid-cols-3 gap-3">
                  {[
                    { id: 'light', label: 'Ljust', icon: Sun },
                    { id: 'dark', label: 'Mörkt', icon: Moon },
                    { id: 'system', label: 'System', icon: Monitor },
                  ].map((theme) => (
                    <button
                      key={theme.id}
                      onClick={() => setProfile({ ...profile, theme: theme.id as any })}
                      className={`p-3 rounded-xl border text-center transition-colors ${
                        profile.theme === theme.id
                          ? 'border-primary bg-primary/5 text-primary'
                          : 'border-border hover:border-primary/30'
                      }`}
                    >
                      <theme.icon size={20} className="mx-auto mb-1" />
                      <span className="text-xs">{theme.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </Card>

          <Card>
            <CardHeader title="Regionala inställningar" subtitle="Språk och tidszon" />
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Språk</label>
                <select
                  value={profile.language}
                  onChange={(e) => setProfile({ ...profile, language: e.target.value })}
                  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>
                  <option value="fi">Suomi</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Tidszon</label>
                <select
                  value={profile.timezone}
                  onChange={(e) => setProfile({ ...profile, timezone: e.target.value })}
                  className="w-full h-10 px-4 rounded-[14px] border bg-surface text-sm"
                >
                  <option value="Europe/Stockholm">Stockholm (CET)</option>
                  <option value="Europe/Oslo">Oslo (CET)</option>
                  <option value="Europe/Copenhagen">Köpenhamn (CET)</option>
                  <option value="Europe/Helsinki">Helsingfors (EET)</option>
                  <option value="UTC">UTC</option>
                </select>
              </div>
            </div>
          </Card>
        </div>
      )}
    </div>
  )
}


