"use client";

import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function StaffLoginPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

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

    try {
      // Call signIn - even if it returns an error, a session may be created
      const result = await signIn("staff-credentials", {
        username: formData.username,
        password: formData.password,
        redirect: false,
      });

      // Wait a moment for session to be set
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // Check if session was actually created (it often is despite CSRF error)
      const sessionRes = await fetch("/api/auth/session");
      const session = await sessionRes.json();

      if (
        session &&
        session.user &&
        session.user.role &&
        session.user.role !== "CUSTOMER"
      ) {
        // Session created successfully - redirect to dashboard
        window.location.href = "/staff/dashboard";
        return;
      }

      // No valid staff session - show error
      setError("Invalid username or password");
      setLoading(false);
    } catch (err) {
      console.error("Login error:", err);
      setError("An error occurred during login. Please try again.");
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-brand-ink via-gray-900 to-brand-ink px-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-white mb-2">Mawidi</h1>
          <p className="text-brand-sand text-sm">Staff Dashboard Access</p>
        </div>

        {/* Login Card */}
        <div className="bg-white rounded-2xl shadow-2xl p-8">
          <div className="mb-6">
            <h2 className="text-2xl font-bold text-brand-ink mb-2">
              Staff Login
            </h2>
            <p className="text-gray-600 text-sm">
              Enter your credentials to access the staff dashboard
            </p>
          </div>

          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
              <p className="text-red-700 text-sm">{error}</p>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Username */}
            <div>
              <label
                htmlFor="username"
                className="block text-sm font-medium text-gray-700 mb-1"
              >
                Username
              </label>
              <input
                id="username"
                type="text"
                value={formData.username}
                onChange={(e) =>
                  setFormData({ ...formData, username: e.target.value })
                }
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent transition"
                placeholder="Enter your username"
                required
                autoComplete="username"
                disabled={loading}
              />
            </div>

            {/* Password */}
            <div>
              <label
                htmlFor="password"
                className="block text-sm font-medium text-gray-700 mb-1"
              >
                Password
              </label>
              <input
                id="password"
                type="password"
                value={formData.password}
                onChange={(e) =>
                  setFormData({ ...formData, password: e.target.value })
                }
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent transition"
                placeholder="Enter your password"
                required
                autoComplete="current-password"
                disabled={loading}
              />
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-brand-green text-white py-3 px-4 rounded-lg font-semibold hover:bg-green-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? "Signing in..." : "Sign In"}
            </button>
          </form>

          {/* Customer Login Link */}
          <div className="mt-6 text-center">
            <p className="text-sm text-gray-600">
              Looking for customer login?{" "}
              <Link
                href="/login"
                className="text-brand-green hover:underline font-medium"
              >
                Click here
              </Link>
            </p>
          </div>
        </div>

        {/* Security Notice */}
        <div className="mt-6 text-center">
          <p className="text-xs text-gray-400">
            This area is restricted to authorized Mawidi staff only.
            <br />
            All access is logged and monitored.
          </p>
        </div>
      </div>
    </div>
  );
}
