import React from "react";
import { toast } from "sonner";

import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { login } from "../../services/accountService";
import { useAuth } from "./AuthProvider";

export function LoginView() {
  const auth = useAuth();
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);

  const canSubmit = Boolean(email.trim() && password.trim() && !submitting);

  const submit = async () => {
    if (!canSubmit) return;
    const emailText = email.trim();
    setSubmitting(true);
    try {
      // Backend keeps `userName` field for compatibility; value must be an email.
      await login({ userName: emailText, password: password.trim() });
      await auth.refresh();
      toast.success("Signed in");
    } catch (e: any) {
      toast.error("Sign-in failed", {
        description: e?.message ? String(e.message) : "Please check your email/password and try again.",
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="w-screen h-screen grid items-center justify-center bg-[#f6f7fb] p-4">
      <div className="w-full max-w-md bg-white border border-gray-200 rounded-2xl shadow-sm p-8">
        <div className="text-center">
          <div className="text-xl font-semibold text-gray-900">Platform Sign In</div>
          <div className="text-sm text-gray-500 mt-1">Your sidebar menu and permissions will load after sign-in.</div>
        </div>

        <div className="mt-6 space-y-4">
          <div className="space-y-2">
            <Label>Email</Label>
            <Input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter your email"
              autoComplete="username"
              onKeyDown={(e) => {
                if (e.key === "Enter") submit();
              }}
            />
          </div>
          <div className="space-y-2">
            <Label>Password</Label>
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter your password"
              autoComplete="current-password"
              onKeyDown={(e) => {
                if (e.key === "Enter") submit();
              }}
            />
          </div>

          <Button className="w-full bg-blue-600 text-white hover:bg-blue-700" disabled={!canSubmit} onClick={submit}>
            {submitting ? "Signing in..." : "Sign In"}
          </Button>
        </div>
      </div>
    </div>
  );
}

