'use client';

import { apiFetch } from '@/lib/api';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Shield, ClipboardCheck, Users, Eye, EyeOff, ChevronRight, AlertCircle,
  MapPin, Bell, BarChart3, UserCog, LogIn
} from 'lucide-react';

const ROLES = [
  {
    id: 'handlaggare',
    label: 'Handl\u00e4ggare',
    subtitle: 'HANDL\u00c4GGARPORTAL',
    description: 'F\u00e4ltarbete, tillsyns\u00e4renden och incheckning',
    icon: ClipboardCheck,
    gradient: 'from-indigo-600 to-purple-600',
    features: [
      { icon: MapPin, text: 'Checka in/ut f\u00f6r tillsyn' },
      { icon: Bell, text: 'N\u00f6dlarm & s\u00e4kerhet' },
    ],
    redirect: '/handlaggare',
  },
  {
    id: 'chef',
    label: 'Chef',
    subtitle: 'CHEFSPORTAL',
    description: '\u00d6verblick \u00f6ver enheten, personalstatus och larm',
    icon: Users,
    gradient: 'from-indigo-600 to-purple-600',
    features: [
      { icon: MapPin, text: 'GPS-sp\u00e5rning i realtid' },
      { icon: BarChart3, text: 'Statistik & rapporter' },
    ],
    redirect: '/chef',
  },
  {
    id: 'admin',
    label: 'Administrat\u00f6r',
    subtitle: 'ADMINPORTAL',
    description: 'Systemadministration, anv\u00e4ndare och enheter',
    icon: Shield,
    gradient: 'from-indigo-600 to-purple-600',
    features: [
      { icon: UserCog, text: 'Handl\u00e4ggarhantering' },
      { icon: BarChart3, text: 'Statistik & rapporter' },
    ],
    redirect: '/admin',
  },
];

// Floating squares component
function FloatingSquares() {
  const squares = [
    { size: 60, top: '8%', left: '12%', rotate: 15, opacity: 0.07, delay: 0 },
    { size: 90, top: '15%', right: '8%', rotate: -20, opacity: 0.05, delay: 1 },
    { size: 45, top: '45%', left: '5%', rotate: 30, opacity: 0.06, delay: 2 },
    { size: 120, bottom: '20%', right: '12%', rotate: -10, opacity: 0.04, delay: 0.5 },
    { size: 70, bottom: '10%', left: '20%', rotate: 45, opacity: 0.06, delay: 1.5 },
    { size: 55, top: '30%', right: '25%', rotate: -35, opacity: 0.05, delay: 3 },
    { size: 80, top: '60%', left: '40%', rotate: 20, opacity: 0.04, delay: 2.5 },
    { size: 40, top: '5%', left: '50%', rotate: -15, opacity: 0.07, delay: 1 },
    { size: 100, bottom: '5%', right: '30%', rotate: 25, opacity: 0.03, delay: 0 },
    { size: 50, top: '75%', left: '15%', rotate: -40, opacity: 0.05, delay: 2 },
  ];

  return (
    <div className="fixed inset-0 overflow-hidden pointer-events-none">
      {squares.map((sq, i) => (
        <div
          key={i}
          className="absolute rounded-xl bg-white animate-float"
          style={{
            width: sq.size,
            height: sq.size,
            top: sq.top,
            left: sq.left,
            right: sq.right,
            bottom: sq.bottom,
            opacity: sq.opacity,
            transform: `rotate(${sq.rotate}deg)`,
            animationDelay: `${sq.delay}s`,
          }}
        />
      ))}
    </div>
  );
}

// Logo component
function AppLogo({ size = 'large', subtitle }) {
  const iconSize = size === 'large' ? 'w-14 h-14' : 'w-10 h-10';
  const textSize = size === 'large' ? 'text-3xl' : 'text-xl';
  const iconPad = size === 'large' ? 'p-3' : 'p-2';

  return (
    <div className="flex flex-col items-center">
      <div className={`${iconPad} rounded-2xl bg-white/10 backdrop-blur-sm mb-3`}>
        <svg className={iconSize} viewBox="0 0 40 40" fill="none">
          <rect x="4" y="4" width="32" height="32" rx="8" stroke="white" strokeWidth="2" opacity="0.3" />
          <path d="M10 20 Q15 12, 20 20 Q25 28, 30 20" stroke="white" strokeWidth="2.5" strokeLinecap="round" fill="none" />
        </svg>
      </div>
      <h1 className={`${textSize} font-bold tracking-tight`}>
        <span className="text-white font-extrabold">TILLSYNS</span>
        <span className="text-white/70">APPEN</span>
      </h1>
      {subtitle && (
        <p className="text-white/50 text-xs tracking-[0.2em] mt-1 uppercase">{subtitle}</p>
      )}
    </div>
  );
}

export default function LoginPage() {
  const router = useRouter();
  const [selectedRole, setSelectedRole] = useState(null);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async (e) => {
    e.preventDefault();
    if (!selectedRole || !email || !password) return;

    setError('');
    setLoading(true);

    try {
      const res = await apiFetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, role: selectedRole.id }),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Inloggningen misslyckades');
        setLoading(false);
        return;
      }

      router.push(selectedRole.redirect);
    } catch {
      setError('Kunde inte ansluta till servern');
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4"
      style={{ background: 'linear-gradient(135deg, #1a1d2e 0%, #252a3a 50%, #1e2235 100%)' }}>
      <FloatingSquares />

      {/* Role selection */}
      {!selectedRole ? (
        <div className="relative z-10 w-full max-w-lg animate-fade-in">
          <div className="text-center mb-10">
            <AppLogo size="large" />
            <p className="text-white/40 mt-4 text-sm">V\u00e4lj din portal f\u00f6r att logga in</p>
          </div>

          <div className="space-y-3">
            {ROLES.map((role) => {
              const Icon = role.icon;
              return (
                <button
                  key={role.id}
                  onClick={() => setSelectedRole(role)}
                  className="w-full flex items-center gap-4 p-4 rounded-2xl
                    bg-white/5 border border-white/10 hover:bg-white/10 hover:border-white/20
                    transition-all duration-300 active:scale-[0.98] cursor-pointer group backdrop-blur-sm"
                >
                  <div className={`flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br ${role.gradient}
                    text-white flex items-center justify-center shadow-lg`}>
                    <Icon className="w-6 h-6" />
                  </div>
                  <div className="flex-1 text-left">
                    <div className="font-semibold text-white">{role.label}</div>
                    <div className="text-sm text-white/50">{role.description}</div>
                  </div>
                  <ChevronRight className="w-5 h-5 text-white/30 group-hover:text-white/60
                    group-hover:translate-x-1 transition-all" />
                </button>
              );
            })}
          </div>

          <p className="text-center text-xs text-white/20 mt-10">
            Tillsynsappen &copy; {new Date().getFullYear()}
          </p>
        </div>
      ) : (
        /* Login form - desktop split layout */
        <div className="relative z-10 w-full max-w-3xl animate-slide-up">
          <div className="flex flex-col md:flex-row rounded-3xl overflow-hidden shadow-2xl">
            {/* Left panel - info */}
            <div className={`bg-gradient-to-br ${selectedRole.gradient} p-8 md:p-10 md:w-5/12
              flex flex-col items-center md:items-start justify-center text-center md:text-left`}>
              <AppLogo size="small" subtitle={selectedRole.subtitle} />

              <p className="text-white/70 text-sm mt-6 hidden md:block">
                Realtids\u00f6versikt av p\u00e5g\u00e5ende tillsyner, handl\u00e4ggarstatus och n\u00f6dlarm.
              </p>

              <div className="hidden md:flex flex-col gap-3 mt-6">
                {selectedRole.features.map((feat, i) => {
                  const FIcon = feat.icon;
                  return (
                    <div key={i} className="flex items-center gap-3 text-white/70 text-sm">
                      <FIcon className="w-4 h-4 text-white/50" />
                      <span>{feat.text}</span>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Right panel - form */}
            <div className="bg-white p-8 md:p-10 md:w-7/12">
              <div className="mb-6">
                <button
                  type="button"
                  onClick={() => { setSelectedRole(null); setError(''); }}
                  className="text-xs text-indigo-500 hover:text-indigo-700 transition-colors cursor-pointer mb-4"
                >
                  &larr; Byt portal
                </button>
                <h2 className="text-2xl font-bold text-gray-900">Logga in</h2>
                <p className="text-gray-500 text-sm mt-1">Ange dina inloggningsuppgifter</p>
              </div>

              {error && (
                <div className="flex items-center gap-2 p-3 mb-4 rounded-xl bg-red-50 text-red-600 text-sm animate-fade-in">
                  <AlertCircle className="w-4 h-4 flex-shrink-0" />
                  {error}
                </div>
              )}

              <form onSubmit={handleLogin}>
                <div className="mb-4">
                  <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">
                    E-post
                  </label>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="namn@tillsyn.se"
                    className="w-full px-4 py-3 rounded-xl border border-gray-200 bg-gray-50
                      focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400
                      transition-all text-gray-900 placeholder:text-gray-400"
                    required
                    autoComplete="email"
                    autoFocus
                  />
                </div>

                <div className="mb-6">
                  <div className="flex items-center justify-between mb-1.5">
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider">
                      L\u00f6senord
                    </label>
                  </div>
                  <div className="relative">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"
                      className="w-full px-4 py-3 rounded-xl border border-gray-200 bg-gray-50
                        focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400
                        transition-all text-gray-900 placeholder:text-gray-400 pr-12"
                      required
                      autoComplete="current-password"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400
                        hover:text-gray-600 transition-colors p-1"
                    >
                      {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                    </button>
                  </div>
                </div>

                <button
                  type="submit"
                  disabled={loading || !email || !password}
                  className="w-full py-3.5 rounded-xl font-semibold text-white transition-all duration-200
                    active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed
                    bg-gray-900 hover:bg-gray-800 flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <span className="flex items-center justify-center gap-2">
                      <svg className="animate-spin w-5 h-5" 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>
                      Loggar in...
                    </span>
                  ) : (
                    <>
                      <LogIn className="w-5 h-5" />
                      Logga in
                    </>
                  )}
                </button>
              </form>

              <p className="text-center text-xs text-gray-400 mt-8">
                Tillsynsappen &copy; {new Date().getFullYear()}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Float animation style */}
      <style jsx global>{`
        @keyframes float {
          0%, 100% { transform: translateY(0) rotate(var(--rotate, 0deg)); }
          50% { transform: translateY(-20px) rotate(var(--rotate, 0deg)); }
        }
        .animate-float {
          animation: float 8s ease-in-out infinite;
        }
      `}</style>
    </div>
  );
}
