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;
  folder: string;
  isImage: boolean;
  previewUrl: string | null;
  visibility: string;
  uploadedBy: string;
  createdAt: string;
};

type Props = {
  files: FileItem[];
  folders: string[];
  currentFolder: string;
};

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, folders, currentFolder }: Props) {
  const [uploading, setUploading] = useState(false);
  const [visibility, setVisibility] = useState<'private' | 'public'>('private');
  const [showForm, setShowForm] = useState(false);
  const [folder, setFolder] = useState(currentFolder);
  const [dragging, setDragging] = 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);
    fd.append('folder', folder);

    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 });
  }

  function handleMove(file: FileItem) {
    const next = prompt('نام پوشه جدید را وارد کنید. برای ریشه خالی بگذارید.', file.folder || '');
    if (next === null) return;
    router.patch(`/school/files/${file.id}/move`, { folder: next }, { preserveScroll: true });
  }

  function changeFolder(next: string) {
    router.get('/school/files', next ? { folder: next } : {}, { 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>

        <section className="panel-card">
          <div className="action-row" style={{ justifyContent: 'space-between', flexWrap: 'wrap' }}>
            <div className="action-row">
              <button className={`btn btn-sm ${currentFolder === '' ? 'btn-primary' : 'btn-ghost'}`} type="button" onClick={() => changeFolder('')}>
                <i className="bi bi-house" /> ریشه
              </button>
              {folders.map((f) => (
                <button key={f} className={`btn btn-sm ${currentFolder === f ? 'btn-primary' : 'btn-ghost'}`} type="button" onClick={() => changeFolder(f)}>
                  <i className="bi bi-folder" /> {f}
                </button>
              ))}
            </div>
            <input className="form-input" style={{ maxWidth: 240 }} value={folder} onChange={(e) => setFolder(e.target.value)} placeholder="پوشه آپلود" />
          </div>
        </section>

        {showForm && (
          <form
            className="panel-card"
            onSubmit={handleUpload}
            onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
            onDragLeave={() => setDragging(false)}
            onDrop={(e) => {
              e.preventDefault();
              setDragging(false);
              if (fileRef.current && e.dataTransfer.files.length > 0) fileRef.current.files = e.dataTransfer.files;
            }}
            style={{ borderColor: dragging ? 'var(--color-primary)' : undefined }}
          >
            <h2 style={{ marginBottom: '1rem' }}>آپلود فایل جدید</h2>
            <div style={{ border: '1px dashed var(--color-border)', borderRadius: 8, padding: '1rem', marginBottom: '1rem', textAlign: 'center', color: 'var(--color-text-muted)' }}>
              فایل را اینجا رها کنید یا از انتخاب فایل استفاده کنید.
            </div>
            <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>
                <input
                  className="form-input"
                  value={folder}
                  onChange={(e) => setFolder(e.target.value)}
                  placeholder="مثلاً امتحانات/دی"
                />
              </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>
                  <th>تاریخ</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {files.map((file) => (
                  <tr key={file.id}>
                    <td>
                      {file.previewUrl ? (
                        <img src={file.previewUrl} alt="" style={{ width: 48, height: 36, objectFit: 'cover', borderRadius: 6, border: '1px solid var(--color-border)' }} />
                      ) : (
                        <span className="icon-badge" style={{ width: 36, height: 36 }}><i className={`bi ${mimeIcon[file.mime] ?? 'bi-file-earmark'}`} /></span>
                      )}
                    </td>
                    <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.82rem' }}>{file.folder || 'ریشه'}</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={() => handleMove(file)}
                        >
                          <i className="bi bi-folder-symlink" />
                        </button>
                        <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>
  );
}
