"use client";

/**
 * Drawer с историей оценок сотрудника (#2556, эпик #2549) —
 * `GET /api/v1/team/employees/{id}/history`.
 */

import { teamErrorMessage, useEmployeeHistory } from "@/lib/team-api";
import type { Employee } from "@/lib/team-api";

function formatDateTime(iso: string): string {
  try {
    return new Date(iso).toLocaleString("ru-RU", {
      day: "2-digit",
      month: "2-digit",
      year: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

function formatPrice(value: number | null): string {
  if (value === null) return "—";
  return `${value.toLocaleString("ru-RU")} ₽`;
}

interface EmployeeHistoryDrawerProps {
  employee: Employee;
  onClose: () => void;
}

export function EmployeeHistoryDrawer({ employee, onClose }: EmployeeHistoryDrawerProps) {
  const historyQ = useEmployeeHistory(employee.id, 50, 0);

  return (
    <>
      <div className="team-drawer-backdrop" role="presentation" onClick={onClose} />
      <aside
        className="team-drawer"
        role="dialog"
        aria-modal="true"
        aria-label={`История оценок сотрудника ${employee.username}`}
      >
        <div className="team-drawer-header">
          <div>
            <h2>История оценок</h2>
            <p className="scraper-hint" style={{ margin: 0 }}>
              {employee.display_name ?? employee.username}
            </p>
          </div>
          <button
            type="button"
            className="team-drawer-close"
            onClick={onClose}
            aria-label="Закрыть"
          >
            ×
          </button>
        </div>

        {historyQ.isPending ? <p className="scraper-hint">Загрузка…</p> : null}
        {historyQ.isError ? (
          <p className="scraper-result scraper-result--error">
            {teamErrorMessage(historyQ.error)}
          </p>
        ) : null}
        {historyQ.data && historyQ.data.length === 0 ? (
          <p className="scraper-hint">У сотрудника пока нет оценок.</p>
        ) : null}

        {historyQ.data && historyQ.data.length > 0 ? (
          <div>
            {historyQ.data.map((entry, i) => (
              <div className="team-history-row" key={entry.estimate_id ?? i}>
                <p className="team-history-address">{entry.address ?? "Адрес не указан"}</p>
                <p className="team-history-meta">
                  {formatDateTime(entry.created_at)}
                  {entry.rooms ? ` · ${entry.rooms}к` : ""}
                  {entry.area_m2 ? ` · ${entry.area_m2} м²` : ""}
                  {entry.median_price !== null ? ` · ${formatPrice(entry.median_price)}` : ""}
                  {entry.confidence ? ` · точность: ${entry.confidence}` : ""}
                  {entry.n_analogs !== null ? ` · аналогов: ${entry.n_analogs}` : ""}
                </p>
              </div>
            ))}
          </div>
        ) : null}
      </aside>
    </>
  );
}
