'use client';

import { ArrowLeft, Eye, EyeOff, GraduationCap, LockKeyhole, ShieldCheck } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState, type FormEvent } from 'react';

interface LoginResponseEnvelope {
  success: boolean;
  data?: {
    authenticated?: boolean;
    user?: {
      roles?: string[];
    };
  };
  error?: {
    code?: string;
    message?: string;
  };
}

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [feedback, setFeedback] = useState<{ kind: 'error' | 'success'; text: string } | null>(
    null,
  );

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setFeedback(null);

    if (!email.trim() || !password) {
      setFeedback({ kind: 'error', text: 'Please enter both your email address and password.' });
      return;
    }

    setSubmitting(true);
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify({
          email: email.trim(),
          password,
        }),
      });

      const payload = (await response.json()) as LoginResponseEnvelope;
      if (!response.ok || !payload.success) {
        setFeedback({
          kind: 'error',
          text: payload.error?.message ?? 'Sign-in could not be completed.',
        });
        return;
      }

      setFeedback({
        kind: 'success',
        text: 'Signed in. Opening your workspace…',
      });
      router.push('/verifications');
    } catch {
      setFeedback({
        kind: 'error',
        text: 'We could not connect. Check your connection and try again.',
      });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="relative isolate flex min-h-screen items-center justify-center overflow-hidden px-4 py-8 sm:px-8">
      <div aria-hidden="true" className="pointer-events-none absolute -top-24 -left-24 -z-10 h-80 w-80 rounded-full bg-[#8d9f5e]/15 blur-3xl" />
      <div aria-hidden="true" className="pointer-events-none absolute -right-24 -bottom-28 -z-10 h-96 w-96 rounded-full bg-[#fec868]/25 blur-3xl" />
      <div className="grid w-full max-w-5xl overflow-hidden rounded-[2rem] border border-[var(--saic-border)] bg-white/75 shadow-[0_30px_90px_rgba(71,60,51,.12)] backdrop-blur-xl md:grid-cols-[1fr_1.05fr]">
        <section className="relative hidden min-h-[620px] flex-col justify-between overflow-hidden bg-[#473c33] p-10 text-white md:flex lg:p-14">
          <div aria-hidden="true" className="absolute -right-28 -bottom-12 h-80 w-80 rounded-full border-[48px] border-[#8d9f5e]/30" />
          <div aria-hidden="true" className="absolute right-16 bottom-28 h-28 w-28 rounded-full bg-[#fec868]/90 blur-[1px]" />
          <div className="relative flex items-center gap-3">
            <span className="grid h-12 w-12 place-items-center rounded-2xl bg-[#8d9f5e] text-white shadow-lg"><GraduationCap className="h-6 w-6" aria-hidden="true" /></span>
            <div><p className="text-sm font-semibold tracking-[.2em]">SAIC CAMPUS</p><p className="mt-0.5 text-xs text-white/65">Institutional administration</p></div>
          </div>
          <div className="relative max-w-md pb-5">
            <p className="mb-4 text-xs font-semibold tracking-[.22em] text-[#fec868] uppercase">A connected campus</p>
            <h2 className="text-4xl leading-tight font-semibold tracking-tight lg:text-5xl">Every day, moving learning forward.</h2>
            <p className="mt-5 max-w-sm text-sm leading-6 text-white/70">A considered workspace for the people and processes that keep SAIC moving.</p>
          </div>
          <p className="relative text-xs text-white/50">SAIC Institute of Management and Technology</p>
        </section>

        <section className="flex min-h-[560px] flex-col justify-center px-6 py-8 sm:px-12 sm:py-12 lg:px-16">
          <div className="mb-10 flex items-center justify-between md:mb-12">
            <div className="flex items-center gap-2 text-xs font-semibold tracking-wide text-[var(--saic-sage-dark)] md:hidden"><GraduationCap className="h-5 w-5" aria-hidden="true" /> SAIC CAMPUS</div>
            <Link href="/" className="ml-auto inline-flex items-center gap-1.5 text-xs font-medium text-[var(--saic-ink-muted)] hover:text-[var(--saic-brown)]"><ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" /><span>Overview</span></Link>
          </div>

          <div className="mb-7">
            <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--saic-border)] bg-[#e8eddc]/70 px-3 py-1.5 text-xs font-medium text-[var(--saic-sage-dark)]"><LockKeyhole className="h-3.5 w-3.5" aria-hidden="true" /> Secure administrator access</span>
            <h1 className="mt-5 text-3xl font-semibold tracking-tight text-[var(--saic-brown)]">Welcome back</h1>
            <p className="mt-2 text-sm leading-6 text-[var(--saic-ink-muted)]">Sign in to continue to your administration workspace.</p>
          </div>

          <form onSubmit={(e) => void handleSubmit(e)} className="space-y-5">
            <div>
              <label htmlFor="admin-email" className="block text-sm font-medium text-[var(--saic-brown)]">Email address</label>
              <input id="admin-email" name="email" type="email" autoComplete="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="name@saic.edu" className="mt-2 block w-full rounded-xl border bg-white/80 px-4 py-3 text-sm text-[var(--saic-brown)] placeholder:text-[#a79d92]" />
            </div>
            <div>
              <label htmlFor="admin-password" className="block text-sm font-medium text-[var(--saic-brown)]">Password</label>
              <div className="relative mt-2">
                <input id="admin-password" name="password" type={showPassword ? 'text' : 'password'} autoComplete="current-password" required value={password} onChange={(e) => setPassword(e.target.value)} className="block w-full rounded-xl border bg-white/80 px-4 py-3 pr-12 text-sm text-[var(--saic-brown)]" />
                <button type="button" aria-label={showPassword ? 'Hide password' : 'Show password'} aria-pressed={showPassword} onClick={() => setShowPassword((show) => !show)} className="absolute inset-y-0 right-0 grid w-12 place-items-center text-[var(--saic-ink-muted)] hover:text-[var(--saic-brown)]">{showPassword ? <EyeOff className="h-4 w-4" aria-hidden="true" /> : <Eye className="h-4 w-4" aria-hidden="true" />}</button>
              </div>
            </div>

          {feedback && (
            <div
                role={feedback.kind === 'error' ? 'alert' : 'status'}
                aria-live={feedback.kind === 'error' ? 'assertive' : 'polite'}
              className={`rounded-lg border px-3 py-2 text-sm ${
                feedback.kind === 'error'
                  ? 'border-red-200 bg-red-50 text-red-800'
                  : 'border-emerald-200 bg-emerald-50 text-emerald-800'
              }`}
            >
              {feedback.text}
            </div>
          )}

          <button
            type="submit"
            disabled={submitting}
            className="w-full rounded-xl bg-[#65783d] px-4 py-3 text-sm font-semibold text-white shadow-[0_8px_18px_rgba(101,120,61,.2)] hover:-translate-y-0.5 hover:bg-[#566833] disabled:opacity-60"
          >
            {submitting ? 'Signing in...' : 'Sign in'}
          </button>
          <p className="flex items-center justify-center gap-1.5 pt-1 text-xs text-[var(--saic-ink-muted)]"><ShieldCheck className="h-3.5 w-3.5 text-[var(--saic-sage-dark)]" aria-hidden="true" /> Secure sign-in through your SAIC account</p>
        </form>
        </section>
      </div>
    </main>
  );
}
