import React, { useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Button } from "../components/ui/Button";
import { Input } from "../components/ui/Input";
import { Card, CardHeader, CardContent } from "../components/ui/Card";
import { login } from "../services/api";
import { useAuthStore } from "../store/auth";
import logo from "../assets/logo.png";

export default function Login() {
  const nav = useNavigate();
  const loc = useLocation();
  const { setTokens } = useAuthStore();

  const [user, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  const onSubmit = async (e) => {
    e.preventDefault();
    setErr("");
    setBusy(true);
    try {
      const data = await login(user, password);
      const access = data.access || data?.tokens?.access;
      const refresh = data.refresh || data?.tokens?.refresh;
      const user0 = data?.user || null;
      if (!access) throw new Error("Login response missing access token.");
      setTokens(access, refresh || "", user0);
      const to = loc.state?.from || "/panel_admin";
      nav(to, { replace: true });
    } catch (e2) {
      setErr(e2?.response?.data?.detail || e2.message || "Login failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="min-h-screen flex md:flex-wrap flex-wrap-reverse dark:text-white dark:bg-[#001F3F] bg-neutral-100 font-iran">
      <div className="flex md:min-h-screen md:w-1/2 w-full">
        <Card className="w-full h-full flex flex-wrap justify-center items-center !border-0 md:rounded-r-xs dark:bg-[#16325b] bg-white">
          <CardContent className="w-full max-w-80">
            <div className="text-2xl text-center mb-3 font-black">ورود مدیر</div>
            <div className="text-base text-center mb-4 dark:text-white text-neutral-500">با اکانت مدیر وارد شوید</div>
            <form onSubmit={onSubmit} className="space-y-3">
              <div>
                <div className="mb-1 text-sm font-semibold dark:text-white text-neutral-600">نام کاربری یا تلفن</div>
                <Input value={user} onChange={(e) => setPhone(e.target.value)} placeholder="Username" />
              </div>
              <div>
                <div className="mb-1 text-sm font-semibold dark:text-white text-neutral-600">رمز عبور</div>
                <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="••••••••" />
              </div>
              {err && <div className="rounded-xl bg-red-50 px-3 py-2 text-sm text-red-700">{err}</div>}
              <Button disabled={busy} className="w-full">
                {busy ? "در حال ورود..." : "ورود"}
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
      <div className="md:w-1/2 w-full">
        <div class="flex justify-center text-center md:h-screen px-4 py-2 items-center">
          <div>
            <img src={logo} class="h-36 mx-auto" alt="" />
            <h1 class="text-4xl uppercase font-black md:block hidden">net nest</h1>
            <h2 class="text-2xl uppercase font-light md:block hidden">in your mind</h2>
          </div>
        </div>
      </div>
    </div>
  );
}
