import { ArrowLeft, CalendarDays, ExternalLink, FolderKanban, Info, Timer } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import Modal from './Modal';
import { formatJalaliDateTime } from '../utils/date';

const typeLabels = {
  meeting: 'جلسه',
  task: 'تسک',
  sprint: 'اسپرینت',
  project: 'پروژه',
  action_item: 'اقدام',
  notification: 'اعلان',
};

export default function EntityPreviewModal({ item, onClose }) {
  const navigate = useNavigate();
  if (!item) return null;

  const title = item.title || item.preview?.title || 'جزئیات';
  const body = item.body || item.preview?.body || item.message;
  const entityType = item.entity_type || item.event_type || 'notification';
  const targetUrl = item.target_url;
  const previewEntries = item.preview && !item.preview.title
    ? Object.entries(item.preview).filter(([, value]) => value !== null && value !== undefined && value !== '')
    : [];

  const goToTarget = () => {
    if (!targetUrl) return;
    onClose();
    navigate(targetUrl);
  };

  return (
    <Modal
      title="مشاهده سریع"
      onClose={onClose}
      size="sm"
      footer={(
        <>
          <button type="button" className="btn btn-secondary" onClick={onClose}>بستن</button>
          {targetUrl && (
            <button type="button" className="btn btn-primary" onClick={goToTarget}>
              رفتن به بخش مربوطه
              <ArrowLeft size={16} />
            </button>
          )}
        </>
      )}
    >
      <article className="entity-preview">
        <div className={`entity-preview-icon tone-${item.color_token || 'primary'}`}>
          <Info size={24} />
        </div>
        <div className="entity-preview-heading">
          <span className="badge badge-primary">{typeLabels[entityType] || entityType}</span>
          <h2>{title}</h2>
          {body && <p>{body}</p>}
        </div>

        <div className="entity-preview-meta">
          {(item.start_at || item.created_at) && (
            <div><CalendarDays size={16} /><span>{formatJalaliDateTime(item.start_at || item.created_at)}</span></div>
          )}
          {item.end_at && (
            <div><Timer size={16} /><span>تا {formatJalaliDateTime(item.end_at)}</span></div>
          )}
          {item.project?.title && (
            <div><FolderKanban size={16} /><span>{item.project.title}</span></div>
          )}
          {item.sprint?.title && (
            <div><ExternalLink size={16} /><span>{item.sprint.title}</span></div>
          )}
        </div>

        {previewEntries.length > 0 && (
          <dl className="entity-preview-details">
            {previewEntries.map(([label, value]) => (
              <div key={label}>
                <dt>{label}</dt>
                <dd>{String(value)}</dd>
              </div>
            ))}
          </dl>
        )}
      </article>
    </Modal>
  );
}
