import React, { useState } from 'react';
import { ChevronDownIcon, PencilSquareIcon, TrashIcon } from '@heroicons/react/24/outline';
import { formatRial } from '../../lib/utils';
import type { InventoryPackage } from '../../hooks/useInventory';
import { usePermissions } from '../../hooks/usePermissions';

interface Props {
  packages: InventoryPackage[];
  onEdit: (pkg: InventoryPackage) => void;
  onDelete: (pkg: InventoryPackage) => void;
}

/** Package cards with an expandable component list — mirrors tauri AddStockView. */
export default function PackagesView({ packages, onEdit, onDelete }: Props) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {packages.map((pkg) => (
        <PackageCard key={pkg.uuid} pkg={pkg} onEdit={onEdit} onDelete={onDelete} />
      ))}
    </div>
  );
}

function PackageCard({ pkg, onEdit, onDelete }: { pkg: InventoryPackage } & Pick<Props, 'onEdit' | 'onDelete'>) {
  const { can } = usePermissions();
  const canUpdate = can('inventory', 'update');
  const canDelete = can('inventory', 'delete');
  const [expanded, setExpanded] = useState(false);
  const divider = <div style={{ height: 1, background: 'var(--border-2)', margin: '8px 0' }} className="inv-divider" />;

  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 16 }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 20, height: 20, background: 'var(--accent)', borderRadius: '50%', flexShrink: 0 }} />
          <span style={{ fontWeight: 500, fontSize: 16, color: 'var(--text)' }}>{pkg.title}</span>
        </div>
        <span
          style={{
            width: 122, height: 34, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            borderRadius: 4, fontWeight: 600, fontSize: 16,
            color: pkg.available ? 'var(--success)' : 'var(--danger)',
            background: pkg.available ? 'var(--success-bg)' : 'var(--danger-bg)',
          }}
        >
          {pkg.available ? 'موجودی کافی' : 'موجودی ناکافی'}
        </span>
      </div>

      {divider}

      {/* Accordion */}
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        style={{
          display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '8px 0',
          background: 'none', border: 'none', cursor: 'pointer',
        }}
      >
        <ChevronDownIcon
          style={{ width: 20, height: 20, color: 'var(--text-2)', transition: 'transform .2s', transform: expanded ? 'rotate(180deg)' : 'none' }}
        />
        <span style={{ fontWeight: 500, fontSize: 14, color: 'var(--text)' }}>اجزای پکیج:</span>
      </button>

      {expanded && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 40, padding: '4px 0 16px' }}>
          {pkg.items.length === 0 ? (
            <span style={{ fontSize: 14, color: 'var(--text-3)' }}>این پکیج کالایی ندارد.</span>
          ) : (
            pkg.items.map((it) => (
              <div key={it.itemUuid} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                <span style={{ color: 'var(--text)', fontWeight: 700, fontSize: 16 }}>{it.name}</span>
                <span
                  style={{
                    height: 24, display: 'inline-flex', alignItems: 'center', padding: '0 10px',
                    background: 'var(--surface-3)', color: 'var(--text-2)', borderRadius: 6, fontWeight: 500, fontSize: 14,
                  }}
                >
                  {it.amount} {it.unit}
                </span>
              </div>
            ))
          )}
        </div>
      )}

      {divider}

      {/* Footer */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontWeight: 700, fontSize: 14, color: 'var(--text)' }}>
          قیمت پکیج: {formatRial(pkg.total)}
        </span>
        <div style={{ display: 'flex', gap: 8 }}>
          {canDelete && (
            <button
              className="btn sm ghost"
              onClick={() => onDelete(pkg)}
              style={{ height: 40, width: 78, border: '1px solid var(--border)', color: 'var(--danger)', gap: 6 }}
            >
              <TrashIcon style={{ width: 16 }} /> حذف
            </button>
          )}
          {canUpdate && (
            <button
              className="btn sm ghost"
              onClick={() => onEdit(pkg)}
              style={{ height: 40, width: 78, border: '1px solid var(--border)', color: 'var(--text-2)', gap: 6 }}
            >
              <PencilSquareIcon style={{ width: 16 }} /> ویرایش
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
