"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Select,
  Textarea,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { emsConfirm } from "@/components/ConfirmDialog";
import { formatBDT, formatDate } from "@/lib/utils";
import { IconAward, IconPlus, IconTrash } from "@/components/icons";

interface Club {
  id: number;
  name: string;
  nameBn: string | null;
  description: string | null;
  _count: { competitions: number };
}

interface Competition {
  id: number;
  name: string;
  nameBn: string | null;
  description: string | null;
  venue: string | null;
  scheduledAt: string;
  status: string;
  club: { id: number; name: string; nameBn: string } | null;
  resultCount: number;
  publishedCount: number;
}

interface ResultRow {
  id?: number;
  studentId: number;
  roll: string;
  name: string;
  nameBn: string | null;
  rank: number;
  points: number;
  remarks: string | null;
  publishedAt: string | null;
}

interface Standing {
  studentId: number;
  roll: string;
  name: string;
  nameBn: string | null;
  points: number;
  wins: number;
  competitions: number;
  history: { competition: string; rank: number; points: number }[];
}

interface StudentLite {
  id: number;
  roll: string;
  name: string;
  nameBn: string | null;
}

const STATUS_BADGE: Record<string, string> = {
  UPCOMING: "badge-primary",
  RUNNING: "badge-warning",
  COMPLETED: "badge-success",
  CANCELLED: "badge-secondary",
};

type Tab = "clubs" | "competitions" | "standings" | "history";

export default function CompetitionsPage() {
  const { t, locale } = useLang();
  const C = t.portal.competitionsPage;
  const { data: clubData, loading, reload: reloadClubs } = useApi<{ clubs: Club[] }>(
    "/api/portal/competitions/clubs"
  );
  const { data: compData, reload: reloadComps } = useApi<{ competitions: Competition[] }>(
    "/api/portal/competitions"
  );
  const { data: studentData } = useApi<{ students: StudentLite[] }>("/api/portal/students");

  const [tab, setTab] = useState<Tab>("clubs");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // club form
  const [clubOpen, setClubOpen] = useState(false);
  const [clubForm, setClubForm] = useState({ name: "", nameBn: "", description: "" });
  const [clubSaving, setClubSaving] = useState(false);

  // competition form
  const [compOpen, setCompOpen] = useState(false);
  const [compForm, setCompForm] = useState({
    name: "", clubId: "", venue: "", scheduledAt: "", description: "",
  });
  const [compSaving, setCompSaving] = useState(false);

  // results editor
  const [resultsFor, setResultsFor] = useState<Competition | null>(null);
  const [resultRows, setResultRows] = useState<ResultRow[]>([]);
  const [addStudentId, setAddStudentId] = useState("");
  const [resultsSaving, setResultsSaving] = useState(false);
  const [publishing, setPublishing] = useState(false);

  // standings
  const [standingsClub, setStandingsClub] = useState("");
  const { data: standingsData, reload: reloadStandings } = useApi<{ standings: Standing[] }>(
    standingsClub
      ? `/api/portal/competitions/standings?clubId=${standingsClub}`
      : "/api/portal/competitions/standings"
  );

  const clubs = clubData?.clubs ?? [];
  const competitions = compData?.competitions ?? [];
  const students = studentData?.students ?? [];

  const statusLabel: Record<string, string> = {
    UPCOMING: C.statusUpcoming,
    RUNNING: C.statusRunning,
    COMPLETED: C.statusCompleted,
    CANCELLED: C.statusCancelled,
  };

  const completed = useMemo(
    () => competitions.filter((c) => c.status === "COMPLETED"),
    [competitions]
  );

  async function createClub(e: React.FormEvent) {
    e.preventDefault();
    setClubSaving(true);
    setMessage(null);
    try {
      await api("/api/portal/competitions/clubs", {
        method: "POST",
        body: JSON.stringify(clubForm),
      });
      setMessage({ type: "success", text: C.clubCreated });
      setClubOpen(false);
      setClubForm({ name: "", nameBn: "", description: "" });
      reloadClubs();
    } catch (err) {
      setMessage({
        type: "error",
        text: err instanceof Error && err.message === "CLUB_EXISTS" ? C.clubExists : t.common.tryAgain,
      });
    } finally {
      setClubSaving(false);
    }
  }

  async function removeClub(club: Club) {
    if (!(await emsConfirm({ message: `${t.common.confirmDelete} — ${club.name}`, danger: true }))) return;
    try {
      await api(`/api/portal/competitions/clubs?id=${club.id}`, { method: "DELETE" });
      setMessage({ type: "success", text: C.clubDeleted });
      reloadClubs();
      reloadComps();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  async function createCompetition(e: React.FormEvent) {
    e.preventDefault();
    setCompSaving(true);
    setMessage(null);
    try {
      await api("/api/portal/competitions", {
        method: "POST",
        body: JSON.stringify({ ...compForm, clubId: Number(compForm.clubId) || null }),
      });
      setMessage({ type: "success", text: C.competitionCreated });
      setCompOpen(false);
      setCompForm({ name: "", clubId: "", venue: "", scheduledAt: "", description: "" });
      reloadComps();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setCompSaving(false);
    }
  }

  async function setStatus(comp: Competition, status: string) {
    try {
      await api("/api/portal/competitions", {
        method: "PATCH",
        body: JSON.stringify({ id: comp.id, status }),
      });
      setMessage({ type: "success", text: C.statusUpdated });
      reloadComps();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  async function removeCompetition(comp: Competition) {
    if (!(await emsConfirm({ message: `${t.common.confirmDelete} — ${comp.name}`, danger: true }))) return;
    try {
      await api(`/api/portal/competitions?id=${comp.id}`, { method: "DELETE" });
      setMessage({ type: "success", text: C.deleted });
      reloadComps();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  function openResults(comp: Competition) {
    setResultsFor(comp);
    setAddStudentId("");
    fetch(`/api/portal/competitions/results?competitionId=${comp.id}`)
      .then((r) => (r.ok ? r.json() : { results: [] }))
      .then((d: { results?: ResultRow[] }) => setResultRows(d.results ?? []))
      .catch(() => setResultRows([]));
  }

  function addParticipant() {
    const student = students.find((s) => String(s.id) === addStudentId);
    if (!student) return;
    if (resultRows.some((r) => r.studentId === student.id)) return;
    setResultRows((rows) => [
      ...rows,
      {
        studentId: student.id,
        roll: student.roll,
        name: student.name,
        nameBn: student.nameBn,
        rank: rows.length + 1,
        points: 0,
        remarks: null,
        publishedAt: null,
      },
    ]);
    setAddStudentId("");
  }

  async function saveResults(e: React.FormEvent) {
    e.preventDefault();
    if (!resultsFor) return;
    setResultsSaving(true);
    setMessage(null);
    try {
      await api("/api/portal/competitions/results", {
        method: "PUT",
        body: JSON.stringify({
          competitionId: resultsFor.id,
          results: resultRows.map((r) => ({
            studentId: r.studentId,
            rank: r.rank,
            points: r.points,
            remarks: r.remarks ?? "",
          })),
        }),
      });
      setMessage({ type: "success", text: C.resultsSaved });
      reloadComps();
      openResults(resultsFor);
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setResultsSaving(false);
    }
  }

  async function togglePublish(publish: boolean) {
    if (!resultsFor) return;
    setPublishing(true);
    setMessage(null);
    try {
      await api("/api/portal/competitions/results", {
        method: "PATCH",
        body: JSON.stringify({ competitionId: resultsFor.id, publish }),
      });
      setMessage({ type: "success", text: publish ? C.published : C.unpublished });
      reloadComps();
      openResults(resultsFor);
      reloadStandings();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setPublishing(false);
    }
  }

  const allPublished =
    resultsFor !== null &&
    resultRows.length > 0 &&
    resultRows.every((r) => r.publishedAt !== null);

  return (
    <div>
      <PageHeader title={C.title} subtitle={C.subtitle} />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      <ul className="nav nav-tabs mb-3">
        {([
          ["clubs", C.tabClubs],
          ["competitions", C.tabCompetitions],
          ["standings", C.tabStandings],
          ["history", C.tabHistory],
        ] as [Tab, string][]).map(([id, label]) => (
          <li className="nav-item" key={id}>
            <button
              className={`nav-link f-w-600 ${tab === id ? "active" : ""}`}
              type="button"
              onClick={() => setTab(id)}
            >
              {label}
            </button>
          </li>
        ))}
      </ul>

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : (
        <>
          {/* ---------------- Clubs ---------------- */}
          {tab === "clubs" && (
            <div className="card">
              <div className="card-header d-flex align-items-center justify-content-between">
                <h5 className="mb-0 f-w-700">{C.tabClubs}</h5>
                <Button size="sm" onClick={() => setClubOpen(true)}>
                  <IconPlus className="svg-14" />
                  <span className="ms-1">{C.newClub}</span>
                </Button>
              </div>
              <div className="card-body">
                {clubs.length === 0 ? (
                  <EmptyState icon={<IconAward />} title={C.noEntries} />
                ) : (
                  <div className="row g-3">
                    {clubs.map((club) => (
                      <div className="col-md-6 col-xl-4" key={club.id}>
                        <div className="ems-club-card">
                          <div className="d-flex align-items-start justify-content-between gap-2">
                            <div className="min-width-0">
                              <h6 className="mb-1 f-w-800">{club.name}</h6>
                              {club.nameBn && (
                                <p className="mb-1 ems-fs-12 text-muted">{club.nameBn}</p>
                              )}
                              {club.description && (
                                <p className="mb-0 ems-fs-12 text-muted">{club.description}</p>
                              )}
                            </div>
                            <button
                              className="ems-price-act danger"
                              title={t.common.delete}
                              onClick={() => removeClub(club)}
                            >
                              <IconTrash className="svg-14" />
                            </button>
                          </div>
                          <span className="badge badge-soft-teal mt-2">
                            {club._count.competitions} × {C.competitionsCount}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* ---------------- Competitions ---------------- */}
          {tab === "competitions" && (
            <div className="card">
              <div className="card-header d-flex align-items-center justify-content-between">
                <h5 className="mb-0 f-w-700">{C.tabCompetitions}</h5>
                <Button size="sm" onClick={() => setCompOpen(true)}>
                  <IconPlus className="svg-14" />
                  <span className="ms-1">{C.newCompetition}</span>
                </Button>
              </div>
              <div className="table-responsive">
                {competitions.length === 0 ? (
                  <div className="card-body">
                    <EmptyState icon={<IconAward />} title={C.upcomingEmpty} />
                  </div>
                ) : (
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{C.competitionName}</th>
                        <th>{C.selectClub}</th>
                        <th>{C.scheduleAt}</th>
                        <th>{C.venue}</th>
                        <th>{t.common.status}</th>
                        <th className="text-end">{t.common.actions}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {competitions.map((c) => (
                        <tr key={c.id}>
                          <td>
                            <p className="mb-0 f-w-700">{locale === "bn" && c.nameBn ? c.nameBn : c.name}</p>
                            {c.resultCount > 0 && (
                              <p className="mb-0 ems-fs-11 text-muted">
                                {c.resultCount} × {C.points} ·{" "}
                                {c.publishedCount > 0 ? (
                                  <span className="text-success">{C.published}</span>
                                ) : (
                                  C.notPublished
                                )}
                              </p>
                            )}
                          </td>
                          <td className="ems-fs-12">
                            {c.club ? (
                              <span className="badge badge-soft-teal">
                                {locale === "bn" && c.club.nameBn ? c.club.nameBn : c.club.name}
                              </span>
                            ) : (
                              <span className="text-muted">{C.standalone}</span>
                            )}
                          </td>
                          <td className="ems-fs-12">{formatDate(c.scheduledAt, locale)}</td>
                          <td className="ems-fs-12">{c.venue ?? "—"}</td>
                          <td>
                            <span className={`badge ${STATUS_BADGE[c.status] ?? "badge-secondary"}`}>
                              {statusLabel[c.status] ?? c.status}
                            </span>
                          </td>
                          <td className="text-end">
                            <div className="d-inline-flex gap-1 flex-wrap justify-content-end">
                              {c.status === "UPCOMING" && (
                                <Button size="sm" variant="warning" onClick={() => setStatus(c, "RUNNING")}>
                                  {C.start}
                                </Button>
                              )}
                              {(c.status === "RUNNING" || c.status === "UPCOMING") && (
                                <Button size="sm" variant="success" onClick={() => setStatus(c, "COMPLETED")}>
                                  {C.complete}
                                </Button>
                              )}
                              {c.status !== "CANCELLED" && c.status !== "COMPLETED" && (
                                <Button size="sm" variant="secondary" onClick={() => setStatus(c, "CANCELLED")}>
                                  {C.cancel}
                                </Button>
                              )}
                              {c.status === "CANCELLED" && (
                                <Button size="sm" variant="secondary" onClick={() => setStatus(c, "UPCOMING")}>
                                  {C.reopen}
                                </Button>
                              )}
                              <Button size="sm" onClick={() => openResults(c)}>
                                {C.manageResults}
                              </Button>
                              <button
                                className="ems-price-act danger"
                                title={t.common.delete}
                                onClick={() => removeCompetition(c)}
                              >
                                <IconTrash className="svg-14" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
          )}

          {/* ---------------- Standings ---------------- */}
          {tab === "standings" && (
            <div className="card">
              <div className="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
                <div>
                  <h5 className="mb-0 f-w-700">{C.standingsTitle}</h5>
                  <p className="mb-0 ems-fs-12 text-muted">{C.standingsHint}</p>
                </div>
                <div style={{ minWidth: 200 }}>
                  <Select
                    wrapperClassName="form-group mb-0"
                    value={standingsClub}
                    onChange={(e) => setStandingsClub(e.target.value)}
                  >
                    <option value="">{C.allClubs}</option>
                    {clubs.map((c) => (
                      <option key={c.id} value={c.id}>{c.name}</option>
                    ))}
                  </Select>
                </div>
              </div>
              <div className="table-responsive">
                {(standingsData?.standings ?? []).length === 0 ? (
                  <div className="card-body">
                    <EmptyState icon={<IconAward />} title={C.noEntries} />
                  </div>
                ) : (
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th style={{ width: 64 }}>#</th>
                        <th>{t.common.name}</th>
                        <th className="text-center">{C.played}</th>
                        <th className="text-center">{C.wins}</th>
                        <th className="text-center">{C.totalPoints}</th>
                        <th>{C.tabHistory}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(standingsData?.standings ?? []).map((s, i) => (
                        <tr key={s.studentId}>
                          <td>
                            <span className={`badge ${i === 0 ? "badge-warning" : i === 1 ? "badge-secondary" : i === 2 ? "badge-danger" : "badge-soft-teal"}`}>
                              {formatBDT(i + 1, locale).replace("৳", "")}
                            </span>
                          </td>
                          <td>
                            <p className="mb-0 f-w-700">{locale === "bn" && s.nameBn ? s.nameBn : s.name}</p>
                            <p className="mb-0 ems-fs-11 text-muted">{t.portal.admissionsPage.roll}: {s.roll}</p>
                          </td>
                          <td className="text-center f-w-700">{s.competitions}</td>
                          <td className="text-center f-w-700">{s.wins}</td>
                          <td className="text-center f-w-800 ems-text-teal">{s.points}</td>
                          <td className="ems-fs-11 text-muted">
                            {s.history
                              .slice(-3)
                              .map((h) => `${h.competition} (#${h.rank}, ${h.points}pt)`)
                              .join(" · ")}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
          )}

          {/* ---------------- History ---------------- */}
          {tab === "history" && (
            <div className="card">
              <div className="card-header">
                <h5 className="mb-0 f-w-700">{C.historyTitle}</h5>
              </div>
              <div className="table-responsive">
                {completed.length === 0 ? (
                  <div className="card-body">
                    <EmptyState icon={<IconAward />} title={C.noEntries} />
                  </div>
                ) : (
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{C.competitionName}</th>
                        <th>{C.selectClub}</th>
                        <th>{C.scheduleAt}</th>
                        <th>{C.winner}</th>
                        <th>{t.common.status}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {completed.map((c) => (
                        <tr key={c.id}>
                          <td className="f-w-700">{locale === "bn" && c.nameBn ? c.nameBn : c.name}</td>
                          <td className="ems-fs-12">
                            {c.club ? (locale === "bn" && c.club.nameBn ? c.club.nameBn : c.club.name) : "—"}
                          </td>
                          <td className="ems-fs-12">{formatDate(c.scheduledAt, locale)}</td>
                          <td className="ems-fs-12">
                            <Button size="sm" variant="secondary" onClick={() => openResults(c)}>
                              {C.manageResults}
                            </Button>
                          </td>
                          <td>
                            <span className={`badge ${STATUS_BADGE[c.status]}`}>
                              {statusLabel[c.status]}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
          )}
        </>
      )}

      {/* New club modal */}
      <Modal open={clubOpen} onClose={() => setClubOpen(false)} title={C.newClub}>
        <form className="theme-form" onSubmit={createClub}>
          <Input
            label={C.clubName}
            required
            value={clubForm.name}
            onChange={(e) => setClubForm({ ...clubForm, name: e.target.value })}
            placeholder="English Language Club"
          />
          <Input
            label={C.clubNameBn}
            value={clubForm.nameBn}
            onChange={(e) => setClubForm({ ...clubForm, nameBn: e.target.value })}
            placeholder="ইংলিশ ল্যাঙ্গুয়েজ ক্লাব"
          />
          <Textarea
            label={C.clubDescription}
            value={clubForm.description}
            onChange={(e) => setClubForm({ ...clubForm, description: e.target.value })}
          />
          <div className="d-flex justify-content-end gap-2 pt-2">
            <Button type="button" variant="secondary" onClick={() => setClubOpen(false)}>
              {t.common.cancel}
            </Button>
            <Button type="submit" loading={clubSaving}>{t.common.create}</Button>
          </div>
        </form>
      </Modal>

      {/* New competition modal */}
      <Modal open={compOpen} onClose={() => setCompOpen(false)} title={C.newCompetition}>
        <form className="theme-form" onSubmit={createCompetition}>
          <Input
            label={C.competitionName}
            required
            value={compForm.name}
            onChange={(e) => setCompForm({ ...compForm, name: e.target.value })}
            placeholder="Inter-class Debate 2026"
          />
          <div className="row">
            <div className="col-md-6">
              <Select
                label={C.selectClub}
                value={compForm.clubId}
                onChange={(e) => setCompForm({ ...compForm, clubId: e.target.value })}
              >
                <option value="">{C.standalone}</option>
                {clubs.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </Select>
            </div>
            <div className="col-md-6">
              <Input
                label={C.scheduleAt}
                type="datetime-local"
                required
                value={compForm.scheduledAt}
                onChange={(e) => setCompForm({ ...compForm, scheduledAt: e.target.value })}
              />
            </div>
            <div className="col-md-6">
              <Input
                label={C.venue}
                value={compForm.venue}
                onChange={(e) => setCompForm({ ...compForm, venue: e.target.value })}
                placeholder="Auditorium"
              />
            </div>
          </div>
          <Textarea
            label={C.clubDescription}
            value={compForm.description}
            onChange={(e) => setCompForm({ ...compForm, description: e.target.value })}
          />
          <div className="d-flex justify-content-end gap-2 pt-2">
            <Button type="button" variant="secondary" onClick={() => setCompOpen(false)}>
              {t.common.cancel}
            </Button>
            <Button type="submit" loading={compSaving}>{t.common.create}</Button>
          </div>
        </form>
      </Modal>

      {/* Point management modal */}
      <Modal
        open={!!resultsFor}
        onClose={() => setResultsFor(null)}
        title={`${C.resultsTitle} — ${resultsFor?.name ?? ""}`}
        wide
      >
        {resultsFor && (
          <form className="theme-form" onSubmit={saveResults}>
            <div className="d-flex flex-wrap align-items-end gap-2 mb-3">
              <div style={{ minWidth: 260, flex: 1 }}>
                <Select
                  label={C.addParticipant}
                  value={addStudentId}
                  onChange={(e) => setAddStudentId(e.target.value)}
                >
                  <option value="">—</option>
                  {students
                    .filter((s) => !resultRows.some((r) => r.studentId === s.id))
                    .map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.roll} — {s.name}
                      </option>
                    ))}
                </Select>
              </div>
              <Button type="button" variant="secondary" onClick={addParticipant} disabled={!addStudentId}>
                <IconPlus className="svg-14" />
                <span className="ms-1">{C.addParticipant}</span>
              </Button>
              <div className="ms-auto d-flex gap-2">
                <Button
                  type="button"
                  variant={allPublished ? "secondary" : "success"}
                  loading={publishing}
                  disabled={resultRows.length === 0}
                  onClick={() => togglePublish(!allPublished)}
                >
                  {allPublished ? C.unpublish : C.publish}
                </Button>
              </div>
            </div>

            {resultRows.length === 0 ? (
              <EmptyState icon={<IconAward />} title={C.noEntries} />
            ) : (
              <div className="table-responsive">
                <table className="table align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{t.common.name}</th>
                      <th style={{ width: 90 }}>{C.rank}</th>
                      <th style={{ width: 110 }}>{C.points}</th>
                      <th>{C.remarks}</th>
                      <th />
                    </tr>
                  </thead>
                  <tbody>
                    {resultRows.map((r, i) => (
                      <tr key={r.studentId}>
                        <td>
                          <p className="mb-0 f-w-700">{r.name}</p>
                          <p className="mb-0 ems-fs-11 text-muted">{r.roll}</p>
                        </td>
                        <td>
                          <input
                            type="number" min={1} className="form-control form-control-sm"
                            value={r.rank}
                            onChange={(e) =>
                              setResultRows((rows) =>
                                rows.map((x, j) => (j === i ? { ...x, rank: Number(e.target.value) } : x))
                              )
                            }
                          />
                        </td>
                        <td>
                          <input
                            type="number" min={0} className="form-control form-control-sm"
                            value={r.points}
                            onChange={(e) =>
                              setResultRows((rows) =>
                                rows.map((x, j) => (j === i ? { ...x, points: Number(e.target.value) } : x))
                              )
                            }
                          />
                        </td>
                        <td>
                          <input
                            type="text" className="form-control form-control-sm"
                            value={r.remarks ?? ""}
                            onChange={(e) =>
                              setResultRows((rows) =>
                                rows.map((x, j) => (j === i ? { ...x, remarks: e.target.value } : x))
                              )
                            }
                          />
                        </td>
                        <td className="text-end">
                          <button
                            type="button"
                            className="ems-price-act danger"
                            onClick={() =>
                              setResultRows((rows) => rows.filter((_, j) => j !== i))
                            }
                          >
                            <IconTrash className="svg-14" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
            <div className="d-flex justify-content-end gap-2 pt-3">
              <Button type="button" variant="secondary" onClick={() => setResultsFor(null)}>
                {t.common.close}
              </Button>
              <Button type="submit" loading={resultsSaving} disabled={resultRows.length === 0}>
                {C.saveResults}
              </Button>
            </div>
          </form>
        )}
      </Modal>
    </div>
  );
}
