"use client";

import { useState } from "react";
import { createClient } from "@/utils/supabase/client";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const router = useRouter();
  const supabase = createClient();

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

    // 1. Authenticate with Supabase Auth
    const { data, error: authError } = await supabase.auth.signInWithPassword({ 
        email, 
        password 
    });

    if (authError) {
      setError(authError.message);
      setLoading(false);
      return;
    }

    // 2. User exists, now check the 'profiles' table for admin status
    if (data?.user) {
      const { data: profile, error: profileError } = await supabase
        .from('profiles')
        .select('is_admin')
        .eq('id', data.user.id)
        .single();

      if (profileError || !profile?.is_admin) {
        // If not an admin, we MUST sign them out immediately 
        // otherwise they stay logged into Supabase Auth as a regular user
        await supabase.auth.signOut();
        setError("Access Denied: You do not have administrative privileges.");
        setLoading(false);
        return;
      }

      // 3. Success: Refresh to update middleware/server components and redirect
      router.refresh();
      router.push("/dashboard");
    }
  };

  return (
    <div className="min-h-screen flex flex-col sm:justify-center items-center pt-6 sm:pt-0 bg-[#f3f4f6] selection:bg-indigo-500 selection:text-white">
      <div className="mb-6">
        <Link href="/" className="flex flex-col items-center gap-2 group">
          <div className="w-12 h-12 bg-indigo-600 rounded-xl flex items-center justify-center shadow-lg shadow-indigo-200 group-hover:scale-105 transition-transform duration-200">
            <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 00-2 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold tracking-tight text-gray-900">
            Omugwor<span className="text-indigo-600">Admin</span>
          </h1>
        </Link>
      </div>

      <div className="w-full sm:max-w-md mt-6 px-6 py-8 bg-white shadow-xl shadow-gray-200/50 overflow-hidden sm:rounded-xl border border-gray-100">
        {error && (
          <div className="mb-4 flex items-center gap-3 p-4 text-sm text-red-800 border border-red-100 rounded-lg bg-red-50 animate-in fade-in slide-in-from-top-1">
            <svg className="w-5 h-5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
            </svg>
            <p className="font-medium">{error}</p>
          </div>
        )}

        <form onSubmit={handleLogin} className="space-y-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 ml-1" htmlFor="email">Email Address</label>
            <input
              id="email"
              type="email"
              required
              autoFocus
              className="mt-1 block w-full px-4 py-3 bg-gray-50 border-gray-200 rounded-lg text-gray-900 focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 border outline-none transition-all duration-200 placeholder:text-gray-400"
              placeholder="admin@omugwor.com"
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 ml-1" htmlFor="password">Password</label>
            <input
              id="password"
              type="password"
              required
              className="mt-1 block w-full px-4 py-3 bg-gray-50 border-gray-200 rounded-lg text-gray-900 focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 border outline-none transition-all duration-200 placeholder:text-gray-400"
              placeholder="••••••••"
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>

          <div className="flex items-center justify-between">
            <label className="inline-flex items-center cursor-pointer group">
              <input type="checkbox" className="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500 w-4 h-4 cursor-pointer" />
              <span className="ml-2 text-sm text-gray-600 group-hover:text-gray-900">Remember me</span>
            </label>
            <Link href="/forgot-password" size-sm className="text-sm font-medium text-indigo-600 hover:text-indigo-500 underline-offset-4 hover:underline">Forgot password?</Link>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full flex justify-center items-center py-3 px-4 rounded-lg shadow-sm text-sm font-bold text-white bg-gray-900 hover:bg-gray-800 focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-all disabled:opacity-70"
          >
            {loading ? (
              <svg className="animate-spin h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
            ) : "Sign In"}
          </button>
        </form>

        <div className="mt-8 pt-6 border-t border-gray-100 text-center">
            <p className="text-sm text-gray-600">New admin? <Link href="/register" className="font-bold text-indigo-600 hover:text-indigo-500">Create an account</Link></p>
        </div>
      </div>
    </div>
  );
}