import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { formatCount } from '@/lib/formatters';

type Voting = {
  id: number;
  title: string;
  range: string;
  status: string;
  votesCount: number;
  startsAt: string;
  endsAt: string;
};

type Props = {
  votings: Voting[];
};

export default function VotingList({ votings }: Props) {
  function handleDelete(voting: Voting) {
    if (!confirm(`آیا می‌خواهید رأی‌گیری «${voting.title}» را حذف کنید؟ این عملیات غیرقابل بازگشت است.`)) return;
    router.delete(`/school/voting/${voting.id}`);
  }

  return (
    <AppLayout title="رأی‌گیری‌ها">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>رأی‌گیری‌های مدرسه</h2>
          </div>
          <a className="btn btn-primary" href="/school/voting/create"><i className="bi bi-plus-circle" /> ساخت رأی‌گیری</a>
        </section>

        {votings.length > 0 ? (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>عنوان</th>
                  <th>دامنه رأی‌دهنده</th>
                  <th>وضعیت</th>
                  <th>تعداد رأی</th>
                  <th>شروع</th>
                  <th>پایان</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {votings.map((voting) => (
                  <tr key={voting.id}>
                    <td>{voting.title}</td>
                    <td>{voting.range}</td>
                    <td>{voting.status}</td>
                    <td>{formatCount(voting.votesCount)}</td>
                    <td>{voting.startsAt}</td>
                    <td>{voting.endsAt}</td>
                    <td>
                      <div className="action-row--compact">
                        <a className="btn btn-ghost btn-sm" href={`/school/voting/${voting.id}/manage`}>
                          <i className="bi bi-gear" /> مدیریت
                        </a>
                        <a className="btn btn-soft btn-sm" href={`/school/voting/results?voting_id=${voting.id}`}>
                          <i className="bi bi-bar-chart" />
                        </a>
                        <button
                          className="btn btn-danger-ghost btn-sm"
                          type="button"
                          onClick={() => handleDelete(voting)}
                        >
                          <i className="bi bi-trash" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>رأی‌گیری ثبت نشده</h2>
            <p>از دکمه ساخت رأی‌گیری شروع کن.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
