import { useState, useEffect, useRef } from 'react';
import api from '../services/api';
import EmptyState from '../components/EmptyState';
import { TableSkeleton } from '../components/LoadingSkeleton';
import ConfirmDialog from '../components/ConfirmDialog';
import toast from 'react-hot-toast';
import { File, Image, FileText, BarChart3, Archive, Folder, Download, Trash2 } from 'lucide-react';
import { formatJalaliDate } from '../utils/date';

export default function Files() {
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [deleting, setDeleting] = useState(null);
  const [search, setSearch] = useState('');
  const [projects, setProjects] = useState([]);
  const [projectId, setProjectId] = useState('');
  const fileRef = useRef(null);

  const fetchFiles = () => {
    setLoading(true);
    const params = {};
    if (search) params.search = search;
    api.get('/files', { params }).then(({ data }) => setFiles(data.data || [])).catch(() => toast.error('خطا')).finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchFiles();
    api.get('/projects', { params: { per_page: 100 } }).then(({ data }) => setProjects(data.data || [])).catch(() => {});
  }, []);

  const handleUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!projectId) {
      toast.error('برای آپلود، ابتدا پروژه را انتخاب کنید');
      if (fileRef.current) fileRef.current.value = '';
      return;
    }
    setUploading(true);
    const formData = new FormData();
    formData.append('file', file);
    formData.append('project_id', projectId);
    try {
      await api.post('/files', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
      toast.success('فایل آپلود شد');
      fetchFiles();
    } catch (err) { toast.error(err.response?.data?.message || 'خطا در آپلود'); } finally { setUploading(false); if (fileRef.current) fileRef.current.value = ''; }
  };

  const handleDelete = async () => {
    try {
      await api.delete(`/files/${deleting.id}`);
      toast.success('فایل حذف شد');
      setDeleting(null);
      fetchFiles();
    } catch { toast.error('خطا'); }
  };

  const formatSize = (bytes) => {
    if (!bytes) return '—';
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
  };

  const getIcon = (mime) => {
    if (!mime) return File;
    if (mime.startsWith('image/')) return Image;
    if (mime.includes('pdf')) return FileText;
    if (mime.includes('word') || mime.includes('document')) return FileText;
    if (mime.includes('sheet') || mime.includes('excel')) return BarChart3;
    if (mime.includes('zip') || mime.includes('rar')) return Archive;
    return File;
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <div>
          <input type="file" ref={fileRef} onChange={handleUpload} style={{ display: 'none' }} />
          <button className="btn btn-primary" onClick={() => fileRef.current?.click()} disabled={uploading}>
            {uploading ? 'در حال آپلود...' : '+ آپلود فایل'}
          </button>
        </div>
      </div>
      <div className="filter-bar">
        <input className="form-input" placeholder="جستجوی فایل..." value={search} onChange={e => setSearch(e.target.value)} style={{ maxWidth: 320 }} onKeyDown={e => e.key === 'Enter' && fetchFiles()} />
        <select className="form-select" value={projectId} onChange={e => setProjectId(e.target.value)}>
          <option value="">انتخاب پروژه برای آپلود</option>
          {projects.map(p => <option key={p.id} value={p.id}>{p.title}</option>)}
        </select>
        <button className="btn btn-secondary btn-sm" onClick={fetchFiles}>جستجو</button>
      </div>

      {loading ? <TableSkeleton rows={6} cols={5} /> : files.length === 0 ? (
        <EmptyState icon={Folder} title="فایلی وجود ندارد" description="هنوز هیچ فایلی آپلود نشده" action={<button className="btn btn-primary" onClick={() => fileRef.current?.click()}>آپلود اولین فایل</button>} />
      ) : (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="table-container">
            <table>
              <thead><tr><th>فایل</th><th>نام</th><th>نوع</th><th>اندازه</th><th>آپلودکننده</th><th>تاریخ</th><th>عملیات</th></tr></thead>
              <tbody>
                {files.map(f => (
                  <tr key={f.id}>
                    <td>{(() => { const Icon = getIcon(f.mime_type || f.type); return <Icon size={22} strokeWidth={1.5} />; })()}</td>
                    <td style={{ fontWeight: 500 }}>{f.original_name || f.name || f.filename}</td>
                    <td style={{ fontSize: '0.8125rem', color: 'var(--gray-500)' }}>{f.mime_type || f.type || '—'}</td>
                    <td>{formatSize(f.size)}</td>
                    <td style={{ fontSize: '0.875rem' }}>{f.uploader?.name || f.user?.name || '—'}</td>
                    <td style={{ fontSize: '0.8125rem', color: 'var(--gray-500)' }}>{formatJalaliDate(f.created_at)}</td>
                    <td>
                      <div style={{ display: 'flex', gap: '0.25rem' }}>
                        <a href={f.file_url || api.defaults.baseURL + `/files/${f.id}`} target="_blank" rel="noreferrer" className="btn btn-sm btn-secondary" download><Download size={14} /></a>
                        <button className="btn btn-sm btn-danger" onClick={() => setDeleting(f)}><Trash2 size={14} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {deleting && <ConfirmDialog title="حذف فایل" message={`آیا از حذف "${deleting.original_name || deleting.name}" اطمینان دارید؟`} onConfirm={handleDelete} onCancel={() => setDeleting(null)} danger />}
    </div>
  );
}
