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

type Homework = {
  id: number;
  title: string;
  description: string | null;
  dueAt: string;
  allowFileUpload: boolean;
  classroom: string;
  subject: string;
  submitted: boolean;
  submissionStatus: string | null;
  submittedAt: string | null;
};

type Props = {
  homeworks: Homework[];
};

const submissionStatusLabel: Record<string, string> = {
  submitted: 'ارسال شده',
  late: 'دیر ارسال',
  reviewed: 'بررسی شد',
  returned: 'بازگشت داده شد',
};

export default function StudentHomeworks({ homeworks }: Props) {
  const [activeId, setActiveId] = useState<number | null>(null);
  const [body, setBody] = useState('');
  const [file, setFile] = useState<File | null>(null);

  function handleSubmit(e: React.FormEvent, homeworkId: number) {
    e.preventDefault();
    const fd = new FormData();
    fd.append('body', body);
    if (file) fd.append('file', file);

    router.post(`/student/homeworks/${homeworkId}`, fd, {
      forceFormData: true,
      onSuccess: () => {
        setActiveId(null);
        setBody('');
        setFile(null);
      },
    });
  }

  return (
    <AppLayout title="تکالیف">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-journal-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />تکالیف</h2>
            <p>تکالیف منتشرشده برای کلاس‌های شما</p>
          </div>
        </section>

        {homeworks.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
              <div className="icon-badge" style={{ width: 56, height: 56, fontSize: '1.5rem', margin: '0 auto 1rem' }}>
                <i className="bi bi-journal-check" />
              </div>
              <h2>تکلیفی وجود ندارد</h2>
              <p>در حال حاضر تکلیف فعالی برای کلاس‌های شما ثبت نشده است.</p>
            </div>
          </section>
        ) : (
          <div className="card-grid">
            {homeworks.map((hw) => (
              <article
                key={hw.id}
                className="panel-card"
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '0.75rem',
                  borderColor: hw.submitted ? 'var(--color-primary-soft)' : undefined,
                  background: hw.submitted ? 'var(--color-primary-soft)' : undefined,
                }}
              >
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '0.75rem' }}>
                  <span className="icon-badge" style={{ flexShrink: 0 }}>
                    <i className="bi bi-journal-check" />
                  </span>
                  <div style={{ flex: 1 }}>
                    <h3 style={{ margin: 0, fontSize: '1rem' }}>{hw.title}</h3>
                    <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginTop: '0.25rem' }}>
                      <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                        <i className="bi bi-door-open" style={{ marginLeft: '0.25rem' }} />{hw.classroom}
                      </span>
                      {hw.subject !== '—' && (
                        <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                          <i className="bi bi-book" style={{ marginLeft: '0.25rem' }} />{hw.subject}
                        </span>
                      )}
                    </div>
                    {hw.description && (
                      <p style={{ margin: '0.4rem 0 0', fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
                        {hw.description}
                      </p>
                    )}
                  </div>
                  {hw.submitted && hw.submissionStatus && (
                    <span className="badge badge-success" style={{ flexShrink: 0 }}>
                      <i className="bi bi-check2-circle" /> {submissionStatusLabel[hw.submissionStatus] ?? hw.submissionStatus}
                    </span>
                  )}
                </div>

                {hw.dueAt !== '—' && (
                  <div style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)' }}>
                    <i className="bi bi-calendar-x" style={{ marginLeft: '0.3rem' }} />
                    مهلت تحویل: {hw.dueAt}
                  </div>
                )}

                {hw.submitted ? (
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '0.4rem',
                      background: 'white',
                      border: '1px solid var(--color-primary-soft)',
                      borderRadius: 'var(--radius-sm)',
                      color: 'var(--color-primary-active)',
                      fontSize: '0.875rem',
                      fontWeight: 700,
                      padding: '0.6rem 0.9rem',
                    }}
                  >
                    <i className="bi bi-check-circle-fill" />
                    تکلیف ارسال شد
                    {hw.submittedAt && (
                      <span style={{ fontWeight: 400, color: 'var(--color-text-muted)', marginRight: 'auto', fontSize: '0.8rem' }}>
                        {hw.submittedAt}
                      </span>
                    )}
                  </div>
                ) : activeId === hw.id ? (
                  <form onSubmit={(e) => handleSubmit(e, hw.id)} style={{ display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
                    <textarea
                      className="form-control"
                      rows={3}
                      placeholder="توضیحات یا متن پاسخ (اختیاری)"
                      value={body}
                      onChange={(e) => setBody(e.target.value)}
                      maxLength={5000}
                    />
                    {hw.allowFileUpload && (
                      <div>
                        <label className="form-label" style={{ fontSize: '0.85rem' }}>
                          <i className="bi bi-paperclip" style={{ marginLeft: '0.3rem' }} />
                          فایل ضمیمه (اختیاری، حداکثر ۱۰ مگابایت)
                        </label>
                        <input
                          type="file"
                          className="form-control"
                          onChange={(e) => setFile(e.target.files?.[0] ?? null)}
                          accept=".pdf,.jpg,.jpeg,.png,.gif,.webp,.doc,.docx,.txt"
                        />
                      </div>
                    )}
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      <button type="submit" className="btn btn-primary btn-sm">
                        <i className="bi bi-send" /> ارسال تکلیف
                      </button>
                      <button
                        type="button"
                        className="btn btn-ghost btn-sm"
                        onClick={() => { setActiveId(null); setBody(''); setFile(null); }}
                      >
                        انصراف
                      </button>
                    </div>
                  </form>
                ) : (
                  <button
                    className="btn btn-primary"
                    style={{ textAlign: 'center' }}
                    onClick={() => setActiveId(hw.id)}
                  >
                    <i className="bi bi-send" /> ارسال پاسخ
                  </button>
                )}
              </article>
            ))}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
