import { FormEvent, useEffect, useState } from "react";
import { Link, router } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { AlertCircle, Loader2, LogIn } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

interface Props {
  onCreateAccount?: () => void;
}

const InlineSignIn = ({ onCreateAccount }: Props) => {
  const { user } = useAuth();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [attempted, setAttempted] = useState(false);

  useEffect(() => {
    if (attempted && !user) {
      setError("This account requires verification. Please use the dedicated login page.");
      setAttempted(false);
    }
  }, [attempted, user]);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch('/login', {
        method: 'POST',
        credentials: 'same-origin',
        redirect: 'manual',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'X-CSRF-TOKEN': csrfToken(),
        },
        body: JSON.stringify({ email: email.trim(), password, remember: false }),
      });

      if (res.status === 422) {
        const data = await res.json().catch(() => ({}));
        const first = (data?.errors && (Object.values(data.errors)[0] as string[])?.[0]) || data?.message;
        setError(first || 'Invalid email or password');
        setSubmitting(false);
        return;
      }

      if (res.type === 'opaqueredirect' || res.status === 302 || res.ok) {
        router.reload({
          only: ['auth'],
          preserveScroll: true,
          onFinish: () => {
            setSubmitting(false);
            setAttempted(true);
          },
        });
        return;
      }

      setError(`Sign-in failed (${res.status}).`);
      setSubmitting(false);
    } catch {
      setError('Network error — please try again.');
      setSubmitting(false);
    }
  };

  return (
    <div className="py-2 space-y-4">
      <div className="text-center">
        <LogIn className="w-10 h-10 text-primary mx-auto mb-2" />
        <h3 className="text-lg font-bold text-foreground">Sign in to Book</h3>
        <p className="text-xs text-muted-foreground mt-1">
          You need an account to book courses. Sign in below to continue with your booking.
        </p>
      </div>

      <form onSubmit={submit} className="space-y-3">
        <div className="space-y-1">
          <Label htmlFor="signin-email" className="text-xs">Email</Label>
          <Input
            id="signin-email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@company.com"
            autoComplete="email"
            required
          />
        </div>
        <div className="space-y-1">
          <Label htmlFor="signin-password" className="text-xs">Password</Label>
          <Input
            id="signin-password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
            required
          />
        </div>

        {error && (
          <div className="flex items-start gap-2 bg-destructive/10 border border-destructive/30 rounded-md p-2.5 text-xs text-destructive">
            <AlertCircle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
            <span>{error}</span>
          </div>
        )}

        <Button type="submit" variant="hero" className="w-full" disabled={submitting || !email.trim() || !password}>
          {submitting ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Signing in…</> : "Sign In & Continue"}
        </Button>
      </form>

      <div className="flex justify-between text-xs text-muted-foreground">
        <Link href="/forgot-password" className="text-primary hover:underline">
          Forgot password?
        </Link>
        <Link href="/login" className="text-muted-foreground hover:text-foreground hover:underline">
          Use login page
        </Link>
      </div>

      <div className="border-t border-border pt-3 text-center text-xs text-muted-foreground">
        New here?{" "}
        <Link href="/register" onClick={onCreateAccount} className="text-primary hover:underline font-medium">
          Create an account
        </Link>
      </div>
    </div>
  );
};

export default InlineSignIn;
