'use client';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/auth-context';
import { AuthShell } from '../shell';
import { Spinner } from '@/components/ui';
import { FloatInput } from '@/components/float';
import { useDialog } from '@/components/dialog';

const schema = z.object({
  email: z.string().email('Enter a valid email address'),
  password: z.string().min(1, 'Password is required'),
});

export default function LoginPage() {
  const router = useRouter();
  const { refresh } = useAuth();
  const { notify } = useDialog();
  const [showPw, setShowPw] = useState(false);
  const [forgotHref, setForgotHref] = useState('/forgot-password');
  useEffect(() => {
    const org = new URLSearchParams(window.location.search).get('org');
    if (org) setForgotHref(`/forgot-password?org=${encodeURIComponent(org)}`);
  }, []);
  const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<z.infer<typeof schema>>({ resolver: zodResolver(schema) });
  const onSubmit = async (v: z.infer<typeof schema>) => {
    try {
      await api.post('/api/v1/auth/login', v);
      await refresh();
      router.push('/dashboard');
    } catch (e: any) { notify(e.message, { tone: 'error' }); }
  };
  return (
    <AuthShell title="Login" subtitle="Welcome back — log in to your workspace">
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
        <FloatInput label="Email" id="login-email" type="email" autoComplete="email" required error={errors.email?.message} {...register('email')} />
        <div className="relative">
          <FloatInput
            label="Password" id="login-password" className="pr-16" type={showPw ? 'text' : 'password'}
            capitalize={false}
            autoComplete="current-password" required error={errors.password?.message} {...register('password')} />
          <button
            type="button" onClick={() => setShowPw(v => !v)}
            aria-pressed={showPw} aria-label={showPw ? 'Hide password' : 'Show password'}
            className="absolute right-2 top-1/2 -translate-y-1/2 text-xs font-semibold px-2 py-1 rounded-lg"
            style={{ color: 'var(--accent)' }}
          >
            {showPw ? 'Hide' : 'Show'}
          </button>
        </div>
        <button className="btn-primary btn-tall w-full" disabled={isSubmitting}>
          {isSubmitting ? <Spinner label="Logging in…" /> : 'Login'}
        </button>
        <p className="text-center">
          <Link href={forgotHref} className="link text-sm">Forgot password?</Link>
        </p>
      </form>
    </AuthShell>
  );
}
