"use client";

import React, { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Building2, Loader2, ArrowLeft } from "lucide-react";

export default function LoginPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Login failed');
        setLoading(false);
        return;
      }

      // Route based on role
      const role = data.user?.role;
      if (role === 'buyer') {
        router.push("/portal");
      } else if (role === 'admin') {
        router.push("/admin");
      } else {
        router.push("/dashboard");
      }
    } catch {
      setError("Login failed. Please try again.");
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-navy-50 to-white px-4 py-8">
      <div className="w-full max-w-md">
        {/* Back to home */}
        <Link
          href="/"
          className="inline-flex items-center gap-1 text-sm text-navy-500 hover:text-navy-700 mb-8 transition-colors"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to home
        </Link>

        <Card className="border-navy-100 shadow-lg">
          <CardHeader className="text-center pb-2">
            <div className="flex justify-center mb-4">
              <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-navy-800">
                <Building2 className="h-6 w-6 text-gold-400" />
              </div>
            </div>
            <CardTitle className="text-2xl">Welcome back</CardTitle>
            <CardDescription>Log in to your CREdispo account</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              {error && (
                <div className="rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">
                  {error}
                </div>
              )}

              <div>
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  placeholder="john@brokerage.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="mt-1.5"
                  required
                />
              </div>

              <div>
                <div className="flex items-center justify-between">
                  <Label htmlFor="password">Password</Label>
                  <button type="button" className="text-xs text-gold-600 hover:text-gold-700">
                    Forgot password?
                  </button>
                </div>
                <Input
                  id="password"
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="mt-1.5"
                  required
                />
              </div>

              <Button type="submit" variant="gold" className="w-full" size="lg" disabled={loading}>
                {loading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Logging in...
                  </>
                ) : (
                  "Log In"
                )}
              </Button>

              <div className="text-center">
                <p className="text-sm text-navy-500">
                  Don&apos;t have an account?{" "}
                  <Link href="/signup" className="font-medium text-gold-600 hover:text-gold-700">
                    Sign up
                  </Link>
                </p>
              </div>

              {/* Demo hint */}
              <div className="mt-4 rounded-lg bg-navy-50 p-3 text-xs text-navy-500">
                <p className="font-medium text-navy-700 mb-1">Demo Accounts</p>
                <p className="mb-1"><strong>Agent:</strong> john@brokerage.com / demo123</p>
                <p className="mb-1"><strong>Admin:</strong> admin@credispo.com / demo123</p>
                <p><strong>Buyer:</strong> robert@thompsonfamily.com / demo123</p>
              </div>
            </form>
          </CardContent>
        </Card>

        {/* Buyer portal link */}
        <div className="mt-6 text-center">
          <Link href="/portal" className="text-sm text-navy-500 hover:text-navy-700 transition-colors">
            Looking for the Buyer Portal? →
          </Link>
        </div>
      </div>
    </div>
  );
}
