'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Mail, Lock, Eye, EyeOff, ArrowRight, Shield } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { adminAuthService } from '@/services/admin-auth.service';
import { getErrorMessage } from '@/lib/errors';

export default function AdminLoginPage() {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const { data } = await adminAuthService.login({ email, password });
      const res = data?.data ?? {};
      const tokens = res.tokens ?? {};
      const accessToken = tokens.accessToken;
      const refreshToken = tokens.refreshToken;

      if (!accessToken) {
        setError('Unable to complete sign in. Please try again.');
        setLoading(false);
        return;
      }

      const admin = res.admin;
      const role = admin?.role ?? 'ADMIN';

      // Store tokens via tokenManager (sets cookie for middleware)
      const { tokenManager } = await import('@/lib/token-manager');
      tokenManager.setTokens(accessToken, refreshToken);

      // Store auth state
      const { useAuthStore } = await import('@/store/auth.store');
      useAuthStore.getState().setAuth(accessToken, role, {
        id: admin?.id ?? '',
        email: admin?.email ?? email,
        firstName: admin?.name,
        lastName: undefined,
        role: role as any,
      }, refreshToken);

      router.replace('/admin/dashboard');
    } catch (err) {
      setError(getErrorMessage(err));
      setLoading(false);
    }
  };

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-surface-sunken px-4 py-10">
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -left-40 -top-40 h-96 w-96 rounded-full bg-primary-500/20 blur-3xl" />
        <div className="absolute -bottom-40 -right-40 h-96 w-96 rounded-full bg-indigo-500/20 blur-3xl" />
        <div className="absolute inset-0 bg-grid opacity-40" />
      </div>

      <div className="relative mx-auto w-full max-w-md">
        <Card className="card-hover">
          <CardHeader>
            <CardTitle className="text-2xl">Admin Sign In</CardTitle>
            <CardDescription className="mt-2">Sign in to the admin control panel</CardDescription>
          </CardHeader>

          {error && (
            <div className="mx-5 mb-2 flex items-start gap-2 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
              <span>{error}</span>
            </div>
          )}

          <form onSubmit={handleSubmit}>
            <CardContent className="space-y-4">
              <div>
                <label htmlFor="admin-email" className="mb-1.5 block text-sm font-medium text-ink">Email</label>
                <Input
                  id="admin-email"
                  type="email"
                  placeholder="admin@example.com"
                  icon={<Mail className="h-4 w-4" />}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  autoComplete="email"
                />
              </div>
              <div>
                <div className="mb-1.5 flex items-center justify-between">
                  <label htmlFor="admin-password" className="text-sm font-medium text-ink">Password</label>
                </div>
                <div className="relative">
                  <Input
                    id="admin-password"
                    type={showPassword ? 'text' : 'password'}
                    placeholder="••••••••"
                    icon={<Lock className="h-4 w-4" />}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                    autoComplete="current-password"
                    className="pr-10"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-faint hover:text-ink"
                    aria-label={showPassword ? 'Hide password' : 'Show password'}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              <Button type="submit" className="w-full" loading={loading}>
                {loading ? 'Signing in...' : 'Sign In'}
                {!loading && <ArrowRight className="h-4 w-4" />}
              </Button>
            </CardContent>
          </form>

          <CardFooter className="flex-col gap-4">
            <p className="text-center text-sm text-ink-muted">
              <Link href="/login" className="font-semibold text-primary-600 hover:underline">Back to user login</Link>
            </p>
          </CardFooter>
        </Card>
      </div>
    </div>
  );
}
