"use client";

import { useEffect, useState } from "react";
import { Edit3, Plus, Trash2 } from "lucide-react";

import { USER_ROLE_OPTIONS, type UserRole } from "@rental/shared";

import {
  createUserRequest,
  deleteUserRequest,
  getUsersRequest,
  type UserRecord,
  updateUserRequest
} from "../../lib/api";
import { useSessionContext } from "../layout/session-provider";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Card } from "../ui/card";
import { Input } from "../ui/input";
import { Modal } from "../ui/modal";

type UserDraft = {
  id?: string;
  name: string;
  email: string;
  password: string;
  role: UserRole;
  isActive: boolean;
};

const blankUser: UserDraft = {
  name: "",
  email: "",
  password: "",
  role: "viewer",
  isActive: true
};

const minimumPasswordLength = 6;

export const UsersAdminPage = () => {
  const { session } = useSessionContext();
  const [users, setUsers] = useState<UserRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [draft, setDraft] = useState<UserDraft | null>(null);

  const refresh = async () => {
    if (!session) {
      return;
    }

    setLoading(true);
    setError(null);

    try {
      setUsers(await getUsersRequest(session));
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Nie udało się pobrać użytkowników");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void refresh();
  }, [session]);

  const draftPassword = draft?.password ?? "";
  const passwordMissingForCreate = !draft?.id && !draftPassword.trim();
  const passwordTooShort = draftPassword.length > 0 && draftPassword.length < minimumPasswordLength;
  const saveDisabled =
    saving || !draft?.name.trim() || !draft?.email.trim() || passwordMissingForCreate || passwordTooShort;

  if (session?.user.role !== "admin") {
    return (
      <Card className="p-6">
        <h2 className="text-xl font-semibold text-ink">Brak dostępu</h2>
        <p className="mt-2 text-sm text-muted">Panel użytkowników jest dostępny wyłącznie dla administratora.</p>
      </Card>
    );
  }

  return (
    <div className="space-y-5">
      <Card className="p-5">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <p className="text-xs uppercase tracking-[0.22em] text-muted">Administracja</p>
            <h2 className="mt-2 text-2xl font-semibold text-ink">Użytkownicy i role</h2>
            <p className="mt-2 text-sm text-muted">Tworzenie, edycja, deaktywacja i usuwanie użytkowników systemu.</p>
          </div>
          <Button onClick={() => setDraft(blankUser)}>
            <Plus className="h-4 w-4" />
            Nowy użytkownik
          </Button>
        </div>
      </Card>

      <Card className="overflow-hidden p-5">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs uppercase tracking-[0.2em] text-muted">Lista</p>
            <h3 className="mt-2 text-lg font-semibold text-ink">{users.length} użytkowników</h3>
          </div>
          <Badge tone="accent">RBAC</Badge>
        </div>

        {loading ? <p className="mt-4 text-sm text-muted">Ładowanie...</p> : null}
        {error ? <p className="mt-4 rounded-2xl bg-[#f8d9d3] px-4 py-3 text-sm text-[#8d2f20]">{error}</p> : null}

        <div className="mt-5 overflow-hidden rounded-[28px] border border-line">
          <div className="hidden grid-cols-[1fr_1fr_0.8fr_0.6fr_0.6fr] gap-3 border-b border-line bg-[#f5efe5] px-4 py-3 text-xs font-semibold uppercase tracking-[0.18em] text-muted lg:grid">
            <div>Użytkownik</div>
            <div>E-mail</div>
            <div>Rola</div>
            <div>Status</div>
            <div></div>
          </div>

          {users.map((user) => (
            <div
              key={user.id}
              className="grid gap-3 border-b border-line/60 bg-white px-4 py-4 lg:grid-cols-[1fr_1fr_0.8fr_0.6fr_0.6fr] lg:items-center"
            >
              <div>
                <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Użytkownik</p>
                <p className="text-sm font-semibold text-ink">{user.name}</p>
                <p className="mt-1 text-xs text-muted">Utworzono: {user.createdAt.slice(0, 10)}</p>
              </div>
              <div>
                <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">E-mail</p>
                <div className="text-sm text-muted">{user.email}</div>
              </div>
              <div>
                <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Rola</p>
                <Badge tone="accent">{user.role}</Badge>
              </div>
              <div>
                <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Status</p>
                <Badge tone={user.isActive ? "success" : "neutral"}>{user.isActive ? "Aktywny" : "Wyłączony"}</Badge>
              </div>
              <div>
                <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Akcje</p>
                <div className="flex justify-start gap-2 lg:justify-end">
                  <Button
                    variant="ghost"
                    onClick={() =>
                      setDraft({
                        id: user.id,
                        name: user.name,
                        email: user.email,
                        password: "",
                        role: user.role,
                        isActive: user.isActive
                      })
                    }
                  >
                    <Edit3 className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    onClick={async () => {
                      if (!session || !window.confirm(`Usunąć użytkownika "${user.name}"?`)) {
                        return;
                      }

                      try {
                        await deleteUserRequest(session, user.id);
                        await refresh();
                      } catch (requestError) {
                        setError(requestError instanceof Error ? requestError.message : "Nie udało się usunąć użytkownika");
                      }
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Modal
        open={Boolean(draft)}
        onClose={() => setDraft(null)}
        title={draft?.id ? "Edytuj użytkownika" : "Dodaj użytkownika"}
        footer={
          <>
            <Button variant="ghost" onClick={() => setDraft(null)}>
              Anuluj
            </Button>
            <Button
              disabled={saveDisabled}
              onClick={async () => {
                if (!session || !draft) {
                  return;
                }

                setSaving(true);

                try {
                  if (draft.id) {
                    await updateUserRequest(session, draft.id, {
                      name: draft.name,
                      email: draft.email,
                      password: draft.password || undefined,
                      role: draft.role,
                      isActive: draft.isActive
                    });
                  } else {
                    await createUserRequest(session, draft);
                  }

                  setDraft(null);
                  await refresh();
                } catch (requestError) {
                  setError(requestError instanceof Error ? requestError.message : "Nie udało się zapisać użytkownika");
                } finally {
                  setSaving(false);
                }
              }}
            >
              {saving ? "Zapisywanie..." : "Zapisz"}
            </Button>
          </>
        }
      >
        <div className="grid gap-4 sm:grid-cols-2">
          <label className="block space-y-2 sm:col-span-2">
            <span className="text-sm font-medium text-ink">Imię i nazwisko</span>
            <Input
              value={draft?.name ?? ""}
              onChange={(event) => setDraft((current) => (current ? { ...current, name: event.target.value } : current))}
            />
          </label>

          <label className="block space-y-2 sm:col-span-2">
            <span className="text-sm font-medium text-ink">E-mail</span>
            <Input
              type="email"
              value={draft?.email ?? ""}
              onChange={(event) => setDraft((current) => (current ? { ...current, email: event.target.value } : current))}
            />
          </label>

          <label className="block space-y-2">
            <span className="text-sm font-medium text-ink">{draft?.id ? "Nowe hasło (opcjonalnie)" : "Hasło"}</span>
            <Input
              minLength={minimumPasswordLength}
              type="password"
              value={draft?.password ?? ""}
              onChange={(event) => setDraft((current) => (current ? { ...current, password: event.target.value } : current))}
            />
            <p className="text-xs text-muted">
              Minimum {minimumPasswordLength} znaków. Przy edycji zostaw puste, jeśli hasło ma pozostać bez zmian.
            </p>
            {passwordTooShort ? (
              <p className="text-xs font-medium text-[#8d2f20]">
                Hasło musi mieć co najmniej {minimumPasswordLength} znaków.
              </p>
            ) : null}
          </label>

          <label className="block space-y-2">
            <span className="text-sm font-medium text-ink">Rola</span>
            <select
              className="w-full rounded-2xl border border-line bg-white px-4 py-2.5 text-sm text-ink outline-none focus:border-accent"
              value={draft?.role ?? "viewer"}
              onChange={(event) =>
                setDraft((current) =>
                  current ? { ...current, role: event.target.value as UserRole } : current
                )
              }
            >
              {USER_ROLE_OPTIONS.map((role) => (
                <option key={role.value} value={role.value}>
                  {role.label}
                </option>
              ))}
            </select>
          </label>

          <label className="flex items-center gap-3 rounded-2xl border border-line bg-white px-4 py-3 sm:col-span-2">
            <input
              checked={draft?.isActive ?? true}
              onChange={(event) => setDraft((current) => (current ? { ...current, isActive: event.target.checked } : current))}
              type="checkbox"
            />
            <span className="text-sm font-medium text-ink">Konto aktywne</span>
          </label>
        </div>
      </Modal>
    </div>
  );
};
