'use client';

// Login page. Uses the bare /api/auth/login endpoint, then a hard
// `window.location` navigation so the new auth cookie is included on
// the next request and middleware sees the user as logged in. A
// router.push would not refresh server components reliably here.

import { useState, FormEvent } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/Button';

export default function LoginPage({
  searchParams,
}: {
  searchParams: { next?: string };
}) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const json = await res.json();
      if (!res.ok || !json.ok) {
        setError(json.error || 'Login failed');
        setLoading(false);
        return;
      }
      const next = searchParams.next || '/dashboard';
      window.location.href = next;
    } catch {
      setError('Network error. Please try again.');
      setLoading(false);
    }
  }

  return (
    <div className="card w-full max-w-sm p-6">
      <div className="mb-6 text-center">
        <div className="mx-auto mb-3 flex w-[200px] items-center justify-center rounded-lg ">
          <img src="/Logo.png" alt="Logo" className="" />
        </div>
        <h1 className="text-lg font-semibold text-gray-900">Support Portal</h1>
        <p className="text-sm text-gray-500">Sign in to continue</p>
      </div>

      <form onSubmit={onSubmit} className="space-y-4">
        <div>
          <label className="label" htmlFor="email">Email</label>
          <input
            id="email"
            type="email"
            className="input"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoFocus
            autoComplete="email"
          />
        </div>
        <div>
          <label className="label" htmlFor="password">Password</label>
          <input
            id="password"
            type="password"
            className="input"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            autoComplete="current-password"
          />
        </div>

        {error ? (
          <div className="rounded-md bg-red-50 p-3 text-sm text-red-700">{error}</div>
        ) : null}

        <Button type="submit" className="w-full" disabled={loading}>
          {loading ? 'Signing in...' : 'Sign in'}
        </Button>
      </form>

      <div className="mt-6 rounded-md bg-gray-50 p-3 text-xs text-gray-600">
        <p className="font-medium text-gray-700">Demo credentials</p>
        <p>Admin: admin@portal.local / Admin@123</p>
        <p>Employee: employee@portal.local / Employee@123</p>
      </div>
    </div>
  );
}
