import { MessageSquarePlus, Plus, Upload } from 'lucide-react';
import { useState } from 'react';
import PwaCreateTaskSheet from './PwaCreateTaskSheet';
import { usePwaNotification } from './PwaNotificationProvider';
import usePwaSheetSwipe from './usePwaSheetSwipe';

const userPermissions = (user) => new Set((user?.roles || []).flatMap((role) => (role.permissions || []).map((permission) => permission.name)));

export default function PwaQuickAction({ user, variant = 'fab' }) {
  const [open, setOpen] = useState(false);
  const [createTaskOpen, setCreateTaskOpen] = useState(false);
  const { notify } = usePwaNotification();
  const { offsetY, isDragging, isClosing, swipeHandlers } = usePwaSheetSwipe(() => setOpen(false), { threshold: 58 });
  const permissions = userPermissions(user);
  const actions = [
    permissions.has('tasks.create') && { key: 'task', label: 'ایجاد تسک', icon: Plus },
    permissions.has('comments.create') && { key: 'comment', label: 'ثبت گزارش کوتاه', icon: MessageSquarePlus },
    permissions.has('files.upload') && { key: 'upload', label: 'آپلود فایل', icon: Upload },
  ].filter(Boolean);

  const handleAction = (action) => {
    setOpen(false);

    if (action.key === 'task') {
      setCreateTaskOpen(true);
      return;
    }

    notify({
      tone: 'info',
      title: action.label,
      message: 'این اقدام در دسترس نیست.',
    });
  };

  return (
    <>
      <button
        type="button"
        className={variant === 'nav' ? 'pwa-nav-create' : 'pwa-fab'}
        onClick={() => {
          if (!actions.length) {
            notify({ tone: 'info', title: 'اقدام سریع', message: 'اقدام سریعی برای حساب شما فعال نیست.' });
            return;
          }
          setOpen(true);
        }}
        aria-label="ایجاد"
      >
        <Plus size={24} />
        {variant === 'nav' && <span>ایجاد</span>}
      </button>
      {open && <button type="button" className="pwa-sheet-backdrop" onClick={() => setOpen(false)} aria-label="بستن" />}
      {open && (
        <section className={`pwa-action-sheet ${isDragging ? 'dragging' : ''} ${isClosing ? 'closing' : ''}`} style={{ '--sheet-offset-y': `${offsetY}px` }} {...swipeHandlers}>
          <div className="pwa-sheet-handle" />
          <h2>اقدام سریع</h2>
          <div className="pwa-action-list">
            {actions.map((action) => {
              const Icon = action.icon;
              return (
                <button key={action.label} type="button" onClick={() => handleAction(action)}>
                  <Icon size={18} />
                  <span>{action.label}</span>
                </button>
              );
            })}
          </div>
        </section>
      )}
      <PwaCreateTaskSheet open={createTaskOpen} onClose={() => setCreateTaskOpen(false)} />
    </>
  );
}
