import { useEffect, useState, useCallback } from 'react';
import api from '../services/api';
import toast from 'react-hot-toast';
import { formatCurrency, formatNumber } from '../utils/formatters';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import { PlusIcon, PencilIcon, TrashIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';

const EMPTY = { name: '', category: '', unit: 'kg', cost_price: '', selling_price: '', stock: 0, status: 'active' };

export default function Products() {
  const [data, setData] = useState({ data: [], total: 0, page: 1, totalPages: 1 });
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('');
  const [page, setPage] = useState(1);
  const [modal, setModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState(EMPTY);
  const [saving, setSaving] = useState(false);
  const [selected, setSelected] = useState(new Set());
  const [bulkDeleting, setBulkDeleting] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const params = { page, limit: 20, search: search || undefined, status: status || undefined };
      const res = await api.get('/products', { params });
      setData(res.data.data);
      setSelected(new Set());
    } finally { setLoading(false); }
  }, [page, search, status]);

  useEffect(() => { fetchData(); }, [fetchData]);

  function openCreate() { setEditing(null); setForm(EMPTY); setModal(true); }
  function openEdit(item) { setEditing(item); setForm({ ...item }); setModal(true); }

  async function handleSave() {
    if (!form.name || !form.unit) return toast.error('Nama dan satuan wajib diisi');
    if (parseFloat(form.selling_price) < 0 || parseFloat(form.cost_price) < 0) return toast.error('Harga tidak boleh negatif');
    setSaving(true);
    try {
      if (editing) {
        await api.put(`/products/${editing.id}`, form);
        toast.success('Produk diperbarui');
      } else {
        await api.post('/products', form);
        toast.success('Produk ditambahkan');
      }
      setModal(false);
      fetchData();
    } finally { setSaving(false); }
  }

  async function handleDelete(item) {
    if (!confirm(`Hapus "${item.name}"?`)) return;
    try {
      const res = await api.delete(`/products/${item.id}`);
      toast.success(res.data?.message || 'Produk dihapus');
      fetchData();
    } catch {}
  }

  async function handleBulkDelete() {
    if (selected.size === 0) return;
    if (!confirm(`Hapus ${selected.size} barang yang dipilih?`)) return;
    setBulkDeleting(true);
    try {
      const results = await Promise.allSettled(
        [...selected].map(id => api.delete(`/products/${id}`))
      );
      const succeeded = results.filter(r => r.status === 'fulfilled').length;
      const failed = results.filter(r => r.status === 'rejected').length;
      if (succeeded > 0) toast.success(`${succeeded} barang berhasil dihapus/dinonaktifkan`);
      if (failed > 0) toast.error(`${failed} barang gagal dihapus`);
      fetchData();
    } finally { setBulkDeleting(false); }
  }

  const rows = data.data;
  const allChecked = rows.length > 0 && rows.every(r => selected.has(r.id));
  const someChecked = rows.some(r => selected.has(r.id));

  function toggleAll() {
    if (allChecked) {
      setSelected(prev => { const s = new Set(prev); rows.forEach(r => s.delete(r.id)); return s; });
    } else {
      setSelected(prev => { const s = new Set(prev); rows.forEach(r => s.add(r.id)); return s; });
    }
  }

  function toggleOne(id) {
    setSelected(prev => {
      const s = new Set(prev);
      s.has(id) ? s.delete(id) : s.add(id);
      return s;
    });
  }

  const f = (k, v) => setForm(p => ({ ...p, [k]: v }));

  return (
    <div className="space-y-4">
      <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
        <div className="flex gap-2 flex-1">
          <div className="relative flex-1 max-w-xs">
            <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input className="input pl-9" placeholder="Cari barang..." value={search}
              onChange={e => { setSearch(e.target.value); setPage(1); }} />
          </div>
          <select className="input w-36" value={status} onChange={e => { setStatus(e.target.value); setPage(1); }}>
            <option value="">Semua Status</option>
            <option value="active">Aktif</option>
            <option value="inactive">Nonaktif</option>
          </select>
        </div>
        <button onClick={openCreate} className="btn-primary">
          <PlusIcon className="w-4 h-4" /> Tambah Barang
        </button>
      </div>

      {selected.size > 0 && (
        <div className="flex items-center justify-between bg-orange-50 border border-orange-200 rounded-xl px-4 py-2.5">
          <span className="text-sm font-medium text-orange-700">
            {selected.size} barang dipilih
          </span>
          <div className="flex items-center gap-2">
            <button onClick={() => setSelected(new Set())}
              className="text-sm text-gray-500 hover:text-gray-700 px-3 py-1.5 rounded-lg hover:bg-gray-100">
              Batal Pilih
            </button>
            <button onClick={handleBulkDelete} disabled={bulkDeleting}
              className="flex items-center gap-1.5 text-sm text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 px-3 py-1.5 rounded-lg transition-colors">
              <TrashIcon className="w-4 h-4" />
              {bulkDeleting ? 'Menghapus...' : `Hapus ${selected.size} Barang`}
            </button>
          </div>
        </div>
      )}

      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="table-th w-10">
                  <input type="checkbox"
                    checked={allChecked}
                    ref={el => { if (el) el.indeterminate = someChecked && !allChecked; }}
                    onChange={toggleAll}
                    className="w-4 h-4 rounded border-gray-300 text-orange-500 cursor-pointer" />
                </th>
                {['Nama Barang','Kategori','Satuan','H. Pokok','H. Jual','Stok','Status','Aksi'].map(h => (
                  <th key={h} className="table-th">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {loading ? (
                <tr><td colSpan={9} className="table-td text-center py-8 text-gray-400">Memuat...</td></tr>
              ) : rows.length === 0 ? (
                <tr><td colSpan={9} className="table-td text-center py-8 text-gray-400">Tidak ada data</td></tr>
              ) : rows.map(item => (
                <tr key={item.id}
                  className={`transition-colors ${selected.has(item.id) ? 'bg-orange-50' : 'hover:bg-gray-50'}`}>
                  <td className="table-td">
                    <input type="checkbox"
                      checked={selected.has(item.id)}
                      onChange={() => toggleOne(item.id)}
                      className="w-4 h-4 rounded border-gray-300 text-orange-500 cursor-pointer" />
                  </td>
                  <td className="table-td font-medium text-gray-900">{item.name}</td>
                  <td className="table-td text-gray-500">{item.category || '-'}</td>
                  <td className="table-td">{item.unit}</td>
                  <td className="table-td">{formatCurrency(item.cost_price)}</td>
                  <td className="table-td font-medium text-orange-600">{formatCurrency(item.selling_price)}</td>
                  <td className="table-td">
                    <span className={item.stock <= 5 ? 'text-red-600 font-bold' : ''}>{formatNumber(item.stock)}</span>
                  </td>
                  <td className="table-td">
                    <span className={item.status === 'active' ? 'badge-green' : 'badge-gray'}>
                      {item.status === 'active' ? 'Aktif' : 'Nonaktif'}
                    </span>
                  </td>
                  <td className="table-td">
                    <div className="flex items-center gap-1">
                      <button onClick={() => openEdit(item)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg"><PencilIcon className="w-4 h-4" /></button>
                      <button onClick={() => handleDelete(item)} className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg"><TrashIcon className="w-4 h-4" /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pagination page={data.page} totalPages={data.totalPages} total={data.total} limit={20} onPageChange={setPage} />
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title={editing ? 'Edit Barang' : 'Tambah Barang'} size="md">
        <div className="space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="label">Nama Barang *</label>
              <input className="input" value={form.name} onChange={e => f('name', e.target.value)} placeholder="Nama barang" />
            </div>
            <div>
              <label className="label">Kategori</label>
              <input className="input" value={form.category} onChange={e => f('category', e.target.value)} placeholder="Kepiting, Minuman..." />
            </div>
            <div>
              <label className="label">Satuan *</label>
              <select className="input" value={form.unit} onChange={e => f('unit', e.target.value)}>
                <option value="kg">Kg</option>
                <option value="gram">Gram</option>
                <option value="pcs">Pcs</option>
                <option value="porsi">Porsi</option>
                <option value="gelas">Gelas</option>
                <option value="liter">Liter</option>
                <option value="botol">Botol</option>
                <option value="bungkus">Bungkus</option>
              </select>
            </div>
            <div>
              <label className="label">Harga Pokok (HPP)</label>
              <input type="number" className="input" value={form.cost_price} onChange={e => f('cost_price', e.target.value)} placeholder="0" />
            </div>
            <div>
              <label className="label">Harga Jual *</label>
              <input type="number" className="input" value={form.selling_price} onChange={e => f('selling_price', e.target.value)} placeholder="0" />
            </div>
            {!editing && (
              <div>
                <label className="label">Stok Awal</label>
                <input type="number" className="input" value={form.stock} onChange={e => f('stock', e.target.value)} placeholder="0" />
              </div>
            )}
            <div>
              <label className="label">Status</label>
              <select className="input" value={form.status} onChange={e => f('status', e.target.value)}>
                <option value="active">Aktif</option>
                <option value="inactive">Nonaktif</option>
              </select>
            </div>
          </div>
          <div className="flex gap-2 pt-2">
            <button onClick={() => setModal(false)} className="btn-secondary flex-1 justify-center">Batal</button>
            <button onClick={handleSave} disabled={saving} className="btn-primary flex-1 justify-center">
              {saving ? 'Menyimpan...' : 'Simpan'}
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
