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

const EMPTY_FORM = { name: '', description: '', selling_price: '', status: 'active', items: [] };

export default function Packages() {
  const [data, setData] = useState({ data: [], total: 0, page: 1, totalPages: 1 });
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [modal, setModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get('/packages', { params: { page, limit: 20 } });
      setData(res.data.data);
    } finally { setLoading(false); }
  }, [page]);

  useEffect(() => { fetchData(); }, [fetchData]);
  useEffect(() => { api.get('/products/active').then(r => setProducts(r.data.data)); }, []);

  function openCreate() {
    setEditing(null);
    setForm({ ...EMPTY_FORM, items: [] });
    setModal(true);
  }

  function openEdit(pkg) {
    setEditing(pkg);
    setForm({
      name: pkg.name, description: pkg.description || '',
      selling_price: pkg.selling_price, status: pkg.status,
      items: (pkg.items || []).filter(i => i && i.product_id).map(i => ({ product_id: i.product_id, qty: i.qty, product_name: i.product_name })),
    });
    setModal(true);
  }

  function addItem() {
    setForm(p => ({ ...p, items: [...p.items, { product_id: '', qty: 1 }] }));
  }

  function updateItem(idx, key, val) {
    setForm(p => {
      const items = [...p.items];
      items[idx] = { ...items[idx], [key]: val };
      if (key === 'product_id') {
        const prod = products.find(pr => pr.id === parseInt(val));
        items[idx].product_name = prod?.name || '';
      }
      return { ...p, items };
    });
  }

  function removeItem(idx) {
    setForm(p => ({ ...p, items: p.items.filter((_, i) => i !== idx) }));
  }

  async function handleSave() {
    if (!form.name || !form.selling_price) return toast.error('Nama dan harga jual wajib diisi');
    if (!form.items.length) return toast.error('Paket harus punya minimal 1 item');
    if (form.items.some(i => !i.product_id || !i.qty)) return toast.error('Semua item harus diisi');
    setSaving(true);
    try {
      const payload = { ...form, items: form.items.map(i => ({ product_id: parseInt(i.product_id), qty: parseFloat(i.qty) })) };
      if (editing) {
        await api.put(`/packages/${editing.id}`, payload);
        toast.success('Paket diperbarui');
      } else {
        await api.post('/packages', payload);
        toast.success('Paket ditambahkan');
      }
      setModal(false);
      fetchData();
    } finally { setSaving(false); }
  }

  async function handleDelete(pkg) {
    if (!confirm(`Hapus paket "${pkg.name}"?`)) return;
    try {
      await api.delete(`/packages/${pkg.id}`);
      toast.success('Paket dihapus');
      fetchData();
    } catch {}
  }

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

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <div />
        <button onClick={openCreate} className="btn-primary"><PlusIcon className="w-4 h-4" /> Tambah Paket</button>
      </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>
                {['Nama Paket','Deskripsi','Item','Harga Jual','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={6} className="table-td text-center py-8 text-gray-400">Memuat...</td></tr>
              ) : data.data.length === 0 ? (
                <tr><td colSpan={6} className="table-td text-center py-8 text-gray-400">Tidak ada paket</td></tr>
              ) : data.data.map(pkg => (
                <tr key={pkg.id} className="hover:bg-gray-50">
                  <td className="table-td font-medium text-gray-900">{pkg.name}</td>
                  <td className="table-td text-gray-500 max-w-xs truncate">{pkg.description || '-'}</td>
                  <td className="table-td">
                    <div className="space-y-0.5">
                      {(pkg.items || []).filter(i => i && i.product_id).map((item, i) => (
                        <div key={i} className="text-xs text-gray-600">• {item.product_name} {item.qty} {item.unit}</div>
                      ))}
                    </div>
                  </td>
                  <td className="table-td font-medium text-orange-600">{formatCurrency(pkg.selling_price)}</td>
                  <td className="table-td">
                    <span className={pkg.status === 'active' ? 'badge-green' : 'badge-gray'}>
                      {pkg.status === 'active' ? 'Aktif' : 'Nonaktif'}
                    </span>
                  </td>
                  <td className="table-td">
                    <div className="flex items-center gap-1">
                      <button onClick={() => openEdit(pkg)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg"><PencilIcon className="w-4 h-4" /></button>
                      <button onClick={() => handleDelete(pkg)} 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 Paket' : 'Tambah Paket'} size="lg">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="label">Nama Paket *</label>
              <input className="input" value={form.name} onChange={e => f('name', e.target.value)} placeholder="Paket A..." />
            </div>
            <div className="col-span-2">
              <label className="label">Deskripsi</label>
              <input className="input" value={form.description} onChange={e => f('description', e.target.value)} placeholder="Deskripsi paket..." />
            </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>
            <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>
            <div className="flex items-center justify-between mb-2">
              <label className="label mb-0">Item Paket *</label>
              <button onClick={addItem} className="text-orange-500 text-sm font-medium hover:text-orange-600">+ Tambah Item</button>
            </div>
            <div className="space-y-2">
              {form.items.map((item, idx) => (
                <div key={idx} className="flex gap-2 items-center">
                  <select className="input flex-1" value={item.product_id}
                    onChange={e => updateItem(idx, 'product_id', e.target.value)}>
                    <option value="">Pilih Produk</option>
                    {products.map(p => <option key={p.id} value={p.id}>{p.name} ({p.unit})</option>)}
                  </select>
                  <input type="number" className="input w-20" min="0.1" step="0.1" value={item.qty}
                    onChange={e => updateItem(idx, 'qty', e.target.value)} placeholder="Qty" />
                  <button onClick={() => removeItem(idx)} className="p-2 text-red-400 hover:text-red-600">
                    <XMarkIcon className="w-4 h-4" />
                  </button>
                </div>
              ))}
              {form.items.length === 0 && (
                <p className="text-sm text-gray-400 text-center py-3 border-2 border-dashed rounded-lg">Klik "+ Tambah Item" untuk menambah</p>
              )}
            </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>
  );
}
