import { AlertCircle, Download, FileUp, MessageCircle } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import { formatJalaliDate, formatJalaliDateTime } from '../utils/date';
import { usePwaNotification } from './PwaNotificationProvider';
import { hasPermission, pwaTaskPriorityLabels, pwaTaskStatusLabels } from './pwaTaskMeta';

export default function PwaTaskDetail() {
  const { id } = useParams();
  const { user } = useAuth();
  const { notify } = usePwaNotification();
  const fileRef = useRef(null);
  const [task, setTask] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [comment, setComment] = useState('');
  const [commentError, setCommentError] = useState('');
  const [submittingComment, setSubmittingComment] = useState(false);
  const [uploading, setUploading] = useState(false);

  const permissions = useMemo(() => ({
    canComment: hasPermission(user, 'comments.create'),
    canUpload: hasPermission(user, 'files.upload'),
    canViewFiles: hasPermission(user, 'files.view'),
  }), [user]);

  const fetchTask = async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get(`/pwa/tasks/${id}`);
      setTask(data.data);
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت جزئیات تسک');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchTask(); }, [id]);

  const submitComment = async (event) => {
    event.preventDefault();
    if (!comment.trim()) {
      setCommentError('متن کامنت الزامی است.');
      return;
    }

    setSubmittingComment(true);
    setCommentError('');
    try {
      const { data } = await api.post(`/pwa/tasks/${id}/comments`, { body: comment.trim() });
      setTask((current) => ({ ...current, comments: [data.data, ...(current.comments || [])] }));
      setComment('');
      notify({ tone: 'success', title: 'کامنت', message: 'کامنت ثبت شد.' });
    } catch (err) {
      setCommentError(err.response?.data?.message || 'ثبت کامنت انجام نشد.');
    } finally {
      setSubmittingComment(false);
    }
  };

  const uploadFile = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);
    setUploading(true);
    try {
      const { data } = await api.post(`/pwa/tasks/${id}/attachments`, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
      setTask((current) => ({ ...current, files: [data.data, ...(current.files || [])] }));
      notify({ tone: 'success', title: 'پیوست', message: 'فایل با موفقیت آپلود شد.' });
    } catch (err) {
      notify({ tone: 'error', title: 'پیوست', message: err.response?.data?.message || 'آپلود فایل انجام نشد.' });
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = '';
    }
  };

  const downloadFile = async (file) => {
    try {
      const response = await api.get(`/pwa/tasks/${task.id}/attachments/${file.id}`, { responseType: 'blob' });
      const url = URL.createObjectURL(response.data);
      const link = document.createElement('a');
      link.href = url;
      link.download = file.original_name || file.name || 'file';
      link.click();
      URL.revokeObjectURL(url);
    } catch (err) {
      notify({ tone: 'error', title: 'پیوست', message: err.response?.data?.message || 'دریافت فایل انجام نشد.' });
    }
  };

  if (loading) return <div className="pwa-skeleton detail" />;

  if (error) {
    return (
      <section className="pwa-state-card error">
        <AlertCircle size={28} />
        <strong>{error}</strong>
        <button type="button" onClick={fetchTask}>تلاش دوباره</button>
      </section>
    );
  }

  return (
    <div className="pwa-task-detail">
      <section className="pwa-detail-card">
        <span className="pwa-eyebrow">{task.project?.title || 'بدون پروژه'}</span>
        <h1>{task.title}</h1>
        <div className="pwa-task-meta">
          <span className={`pwa-chip priority-${task.priority || 'medium'}`}>{pwaTaskPriorityLabels[task.priority] || 'معمولی'}</span>
          <span className="pwa-chip">{pwaTaskStatusLabels[task.status] || task.status || 'نامشخص'}</span>
        </div>
        <p>{task.description || 'توضیحی برای این تسک ثبت نشده است.'}</p>
      </section>

      <section className="pwa-detail-grid">
        <Info label="مسئول" value={task.assignee?.name || 'بدون مسئول'} />
        <Info label="گزارش‌دهنده" value={task.reporter?.name || 'نامشخص'} />
        <Info label="مهلت انجام" value={formatJalaliDate(task.due_date, 'بدون موعد')} />
        <Info label="تاریخ ایجاد" value={formatJalaliDate(task.created_at, 'نامشخص')} />
      </section>

      <section className="pwa-card-section">
        <div className="pwa-section-title">
          <h2>کامنت‌ها</h2>
          <span>{task.comments?.length || 0} مورد</span>
        </div>
        {permissions.canComment && (
          <form className="pwa-comment-form" onSubmit={submitComment}>
            <textarea value={comment} onChange={(event) => setComment(event.target.value)} placeholder="کامنت جدید بنویسید" rows={3} />
            {commentError && <small>{commentError}</small>}
            <button type="submit" disabled={submittingComment}><MessageCircle size={16} /> {submittingComment ? 'در حال ثبت...' : 'ثبت کامنت'}</button>
          </form>
        )}
        <div className="pwa-comment-list">
          {(task.comments || []).length ? task.comments.map((item) => (
            <article key={item.id} className="pwa-comment-item">
              <strong>{item.user?.name || 'کاربر'}</strong>
              <p>{item.body}</p>
              <small>{formatJalaliDateTime(item.created_at)}</small>
            </article>
          )) : <div className="pwa-empty-inline">کامنتی ثبت نشده است.</div>}
        </div>
      </section>

      <section className="pwa-card-section">
        <div className="pwa-section-title">
          <h2>فایل‌های پیوست</h2>
          <span>{task.files?.length || 0} مورد</span>
        </div>
        {permissions.canUpload && (
          <label className="pwa-upload-button">
            <FileUp size={16} />
            {uploading ? 'در حال آپلود...' : 'آپلود فایل'}
            <input ref={fileRef} type="file" onChange={uploadFile} disabled={uploading} />
          </label>
        )}
        <div className="pwa-file-list">
          {!permissions.canViewFiles ? (
            <div className="pwa-empty-inline">برای مشاهده فایل‌ها دسترسی ندارید.</div>
          ) : (task.files || []).length ? task.files.map((file) => (
            <button key={file.id} type="button" onClick={() => downloadFile(file)} className="pwa-file-item">
              <Download size={16} />
              <span>{file.original_name || file.name}</span>
            </button>
          )) : <div className="pwa-empty-inline">فایلی پیوست نشده است.</div>}
        </div>
      </section>
    </div>
  );
}

function Info({ label, value }) {
  return (
    <div className="pwa-detail-info">
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}
