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

type FileItem = {
  id: number;
  name: string;
  mime: string;
  size: string;
  visibility: string;
  uploadedBy: string;
  createdAt: string;
};

type Props = {
  files: FileItem[];
};

const mimeIcon: Record<string, string> = {
  'application/pdf': 'bi-file-earmark-pdf',
  'image/jpeg': 'bi-file-earmark-image',
  'image/png': 'bi-file-earmark-image',
  'image/gif': 'bi-file-earmark-image',
  'text/plain': 'bi-file-earmark-text',
  'text/csv': 'bi-file-earmark-spreadsheet',
  'application/vnd.ms-excel': 'bi-file-earmark-spreadsheet',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'bi-file-earmark-spreadsheet',
  'application/msword': 'bi-file-earmark-word',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'bi-file-earmark-word',
};

export default function SchoolFiles({ files }: Props) {
  const [uploading, setUploading] = useState(false);
  const [visibility, setVisibility] = useState<'private' | 'public'>('private');
  const [showForm, setShowForm] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  function handleUpload(e: React.FormEvent) {
    e.preventDefault();
    const file = fileRef.current?.files?.[0];
    if (!file) return;

    const fd = new FormData();
    fd.append('file', file);
    fd.append('visibility', visibility);

    setUploading(true);
    router.post('/school/files', fd, {
      forceFormData: true,
      onFinish: () => {
        setUploading(false);
        setShowForm(false);
        if (fileRef.current) fileRef.current.value = '';
      },
    });
  }

  function handleDelete(file: FileItem) {
    if (!confirm(`حذف «${file.name}»؟`)) return;
    router.delete(`/school/files/${file.id}`, { preserveScroll: true });
  }

  return (
    <AppLayout title="فایل‌ها">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>مدیریت فایل‌ها</h2>
            <p>آپلود، مشاهده و مدیریت فایل‌های مدرسه. حداکثر حجم: ۱۰ مگابایت.</p>
          </div>
          <button className="btn btn-primary" type="button" onClick={() => setShowForm(!showForm)}>
            <i className="bi bi-upload" /> آپلود فایل
          </button>
        </section>

        {showForm && (
          <form className="panel-card" onSubmit={handleUpload}>
            <h2 style={{ marginBottom: '1rem' }}>آپلود فایل جدید</h2>
            <div className="form-grid">
              <div>
                <label
                  style={{
                    display: 'block',
                    fontWeight: 700,
                    marginBottom: '0.4rem',
                    fontSize: '0.9rem',
                    color: 'var(--color-text)',
                  }}
                >
                  انتخاب فایل
                </label>
                <input
                  ref={fileRef}
                  type="file"
                  accept=".pdf,.jpg,.jpeg,.png,.gif,.doc,.docx,.xls,.xlsx,.txt,.csv"
                  required
                  style={{
                    background: 'var(--color-bg-soft)',
                    border: '1px solid var(--color-border)',
                    borderRadius: 'var(--radius-sm)',
                    padding: '0.55rem 0.75rem',
                    width: '100%',
                    fontSize: '0.9rem',
                  }}
                />
              </div>
              <div>
                <label
                  style={{
                    display: 'block',
                    fontWeight: 700,
                    marginBottom: '0.4rem',
                    fontSize: '0.9rem',
                    color: 'var(--color-text)',
                  }}
                >
                  دسترسی
                </label>
                <select
                  value={visibility}
                  onChange={(e) => setVisibility(e.target.value as 'private' | 'public')}
                  style={{
                    background: 'var(--color-bg-soft)',
                    border: '1px solid var(--color-border)',
                    borderRadius: 'var(--radius-sm)',
                    padding: '0.55rem 0.75rem',
                    width: '100%',
                    fontSize: '0.9rem',
                    color: 'var(--color-text)',
                  }}
                >
                  <option value="private">خصوصی (فقط ادمین)</option>
                  <option value="public">عمومی (کاربران مدرسه)</option>
                </select>
              </div>
            </div>
            <div className="action-row" style={{ marginTop: '1rem' }}>
              <button className="btn btn-primary" type="submit" disabled={uploading}>
                {uploading ? <><i className="bi bi-arrow-repeat" /> در حال آپلود...</> : <><i className="bi bi-upload" /> آپلود</>}
              </button>
              <button className="btn btn-ghost" type="button" onClick={() => setShowForm(false)}>لغو</button>
            </div>
          </form>
        )}

        {files.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>
                {files.map((file) => (
                  <tr key={file.id}>
                    <td>
                      <i
                        className={`bi ${mimeIcon[file.mime] ?? 'bi-file-earmark'}`}
                        style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }}
                      />
                      <span style={{ fontSize: '0.875rem' }}>{file.name}</span>
                    </td>
                    <td style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                      {file.mime.split('/')[1] ?? file.mime}
                    </td>
                    <td style={{ fontSize: '0.85rem' }}>{file.size}</td>
                    <td>
                      <span className={`badge ${file.visibility === 'عمومی' ? 'badge-success' : 'badge-muted'}`}>
                        {file.visibility}
                      </span>
                    </td>
                    <td style={{ fontSize: '0.85rem' }}>{file.uploadedBy}</td>
                    <td style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)' }}>{file.createdAt}</td>
                    <td>
                      <div className="action-row--compact">
                        <a
                          className="btn btn-soft btn-sm"
                          href={`/school/files/${file.id}/download`}
                          download
                        >
                          <i className="bi bi-download" />
                        </a>
                        <button
                          className="btn btn-ghost btn-sm"
                          type="button"
                          onClick={() => handleDelete(file)}
                        >
                          <i className="bi bi-trash" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <div
              style={{
                alignItems: 'center',
                display: 'flex',
                flexDirection: 'column',
                gap: '1rem',
                padding: '2rem 1rem',
                textAlign: 'center',
              }}
            >
              <div className="icon-badge" style={{ width: 56, height: 56, fontSize: '1.5rem' }}>
                <i className="bi bi-folder2-open" />
              </div>
              <h2>هنوز فایلی آپلود نشده</h2>
              <p>از دکمه «آپلود فایل» فایل‌های مدرسه را اضافه کنید.</p>
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
