import { useForm, router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { TextInput } from '@/Components/Forms/TextInput';

type Candidate = {
  id: number;
  name: string;
  slogan: string;
  status: string;
};

type Voting = {
  id: number;
  title: string;
  description: string;
  status: string;
  statusLabel: string;
};

type Props = {
  voting: Voting;
  candidates: Candidate[];
};

const statusOptions = [
  { value: 'draft', label: 'پیش‌نویس' },
  { value: 'published', label: 'فعال (قابل رأی‌دهی)' },
  { value: 'paused', label: 'متوقف' },
  { value: 'closed', label: 'پایان‌یافته' },
];

export default function VotingManage({ voting, candidates }: Props) {
  const candidateForm = useForm({ display_name: '', slogan: '', description: '' });
  const statusForm = useForm({ status: voting.status });

  function handleAddCandidate(event: React.FormEvent) {
    event.preventDefault();
    candidateForm.post(`/school/voting/${voting.id}/candidates`, {
      preserveScroll: true,
      onSuccess: () => candidateForm.reset(),
    });
  }

  function handleDeleteCandidate(id: number, name: string) {
    if (!confirm(`آیا می‌خواهید کاندیدای «${name}» را حذف کنید؟`)) return;
    router.delete(`/school/voting/${voting.id}/candidates/${id}`, { preserveScroll: true });
  }

  function handleStatusChange(event: React.FormEvent) {
    event.preventDefault();
    statusForm.patch(`/school/voting/${voting.id}/status`, { preserveScroll: true });
  }

  return (
    <AppLayout title={`مدیریت رأی‌گیری`}>
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>{voting.title}</h2>
            <p>وضعیت فعلی: <strong>{voting.statusLabel}</strong></p>
          </div>
          <div className="action-row">
            <a className="btn btn-ghost" href="/school/voting"><i className="bi bi-arrow-right" /> بازگشت</a>
            <a className="btn btn-soft" href={`/school/voting/results?voting_id=${voting.id}`}>نتایج</a>
          </div>
        </section>

        <form className="panel-card" onSubmit={handleStatusChange}>
          <h2>تغییر وضعیت</h2>
          <p>وقتی رأی‌گیری روی «فعال» باشد دانش‌آموزان می‌توانند رأی دهند.</p>
          <div className="form-grid">
            <label className="form-field">
              <span>وضعیت</span>
              <select
                className="form-select"
                value={statusForm.data.status}
                onChange={(e) => statusForm.setData('status', e.target.value)}
              >
                {statusOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </label>
          </div>
          <button className="btn btn-primary" disabled={statusForm.processing} type="submit">
            <i className="bi bi-check-circle" /> ذخیره وضعیت
          </button>
        </form>

        <form className="panel-card" onSubmit={handleAddCandidate}>
          <h2>افزودن کاندیدا</h2>
          <div className="form-grid">
            <TextInput label="نام نمایشی کاندیدا" value={candidateForm.data.display_name} onChange={(e) => candidateForm.setData('display_name', e.target.value)} error={candidateForm.errors.display_name} />
            <TextInput label="شعار انتخاباتی" value={candidateForm.data.slogan} onChange={(e) => candidateForm.setData('slogan', e.target.value)} />
          </div>
          <button className="btn btn-primary" disabled={candidateForm.processing} type="submit">
            <i className="bi bi-person-plus" /> افزودن کاندیدا
          </button>
        </form>

        {candidates.length > 0 ? (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>نام کاندیدا</th>
                  <th>شعار</th>
                  <th>وضعیت</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {candidates.map((candidate) => (
                  <tr key={candidate.id}>
                    <td>{candidate.name}</td>
                    <td>{candidate.slogan || '—'}</td>
                    <td>{candidate.status === 'approved' ? 'تایید شده' : candidate.status}</td>
                    <td>
                      <button
                        className="btn btn-danger-ghost btn-sm"
                        type="button"
                        onClick={() => handleDeleteCandidate(candidate.id, candidate.name)}
                      >
                        <i className="bi bi-trash" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>کاندیدایی ثبت نشده</h2>
            <p>از فرم بالا کاندیداها را اضافه کن، سپس رأی‌گیری را منتشر کن.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
