import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { JalaliDatePicker } from '@/Components/Forms/JalaliDatePicker';
import { useState } from 'react';

type Option = { value: number; label: string };
type Award = { id: number; title: string; description: string | null; color: string; awardedAt: string; student: string };
type Props = { awards: Award[]; students: Option[] };

const colors = ['#0EA678', '#2563eb', '#f59e0b', '#ef4444', '#7c3aed'];

export default function Awards({ awards, students }: Props) {
  const [awardedAt, setAwardedAt] = useState('');

  function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(e.currentTarget));
    data.awarded_at = awardedAt;
    router.post('/school/awards', data, { preserveScroll: true });
    e.currentTarget.reset();
    setAwardedAt('');
  }

  return (
    <AppLayout title="تقدیرنامه‌ها">
      <div className="page-stack">
        <section className="section-header"><div><h2>جایزه و تقدیرنامه</h2><p>ثبت نشان افتخار برای پروفایل دانش‌آموز</p></div></section>
        <form className="panel-card" onSubmit={submit}>
          <div className="form-grid">
            <select className="form-select" name="student_id" required><option value="">دانش‌آموز</option>{students.map((s) => <option key={s.value} value={s.value}>{s.label}</option>)}</select>
            <input className="form-input" name="title" required placeholder="عنوان تقدیر" />
            <JalaliDatePicker label="تاریخ تقدیر" value={awardedAt} onChange={setAwardedAt} />
            <select className="form-select" name="badge_color" defaultValue={colors[0]}>{colors.map((color) => <option key={color} value={color}>{color}</option>)}</select>
            <textarea className="form-input" name="description" placeholder="توضیح" style={{ gridColumn: '1 / -1' }} />
          </div>
          <button className="btn btn-primary" type="submit" style={{ marginTop: 16 }}><i className="bi bi-award" /> ثبت تقدیر</button>
        </form>
        <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
          <table className="data-table">
            <thead><tr><th>نشان</th><th>دانش‌آموز</th><th>تاریخ</th><th>توضیح</th></tr></thead>
            <tbody>
              {awards.map((award) => (
                <tr key={award.id}>
                  <td><span className="badge" style={{ background: award.color, color: '#fff' }}><i className="bi bi-award" /> {award.title}</span></td>
                  <td>{award.student}</td>
                  <td>{award.awardedAt}</td>
                  <td>{award.description || '—'}</td>
                </tr>
              ))}
              {awards.length === 0 && <tr><td colSpan={4} style={{ textAlign: 'center' }}>هنوز تقدیری ثبت نشده است.</td></tr>}
            </tbody>
          </table>
        </section>
      </div>
    </AppLayout>
  );
}
