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

export default function StockManagement() {
  const [data, setData] = useState({ data: [], total: 0, page: 1, totalPages: 1 });
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [modal, setModal] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [form, setForm] = useState({ movement_type: 'adjustment_in', qty: '', reason: '' });
  const [saving, setSaving] = useState(false);

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

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

  function openAdjust(product) {
    setSelectedProduct(product);
    setForm({ movement_type: 'adjustment_in', qty: '', reason: '' });
    setModal(true);
  }

  async function handleAdjust() {
    if (!form.qty || parseFloat(form.qty) <= 0) return toast.error('Qty harus lebih dari 0');
    setSaving(true);
    try {
      await api.post('/stock/adjust', {
        product_id: selectedProduct.id,
        movement_type: form.movement_type,
        qty: parseFloat(form.qty),
        reason: form.reason,
      });
      toast.success('Stok berhasil disesuaikan');
      setModal(false);
      fetchData();
    } finally { setSaving(false); }
  }

  return (
    <div className="space-y-4">
      <div className="flex gap-2">
        <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>
      </div>

      <div className="card overflow-hidden">
        <div className="px-5 py-3 border-b bg-gray-50">
          <p className="text-sm font-medium text-gray-600">Klik tombol "Sesuaikan" untuk menambah atau mengurangi stok secara manual</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>
                {['Nama Barang','Kategori','Satuan','Stok Saat Ini','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 data</td></tr>
              ) : data.data.map(item => (
                <tr key={item.id} className="hover:bg-gray-50">
                  <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">
                    <span className={`font-bold text-base ${parseFloat(item.stock) <= 5 ? 'text-red-600' : parseFloat(item.stock) <= 20 ? 'text-yellow-600' : 'text-gray-900'}`}>
                      {formatNumber(item.stock)}
                    </span>
                    {parseFloat(item.stock) <= 5 && <span className="ml-2 badge-red">Hampir habis</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">
                    <button onClick={() => openAdjust(item)}
                      className="px-3 py-1.5 bg-orange-50 text-orange-600 border border-orange-200 rounded-lg text-xs font-medium hover:bg-orange-100">
                      Sesuaikan
                    </button>
                  </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="Penyesuaian Stok" size="sm">
        {selectedProduct && (
          <div className="space-y-4">
            <div className="bg-gray-50 rounded-lg p-3 text-sm">
              <p className="font-medium text-gray-800">{selectedProduct.name}</p>
              <p className="text-gray-500">Stok saat ini: <strong>{formatNumber(selectedProduct.stock)} {selectedProduct.unit}</strong></p>
            </div>

            <div>
              <label className="label">Jenis Penyesuaian *</label>
              <div className="grid grid-cols-2 gap-2">
                {[
                  { value: 'adjustment_in', label: 'Tambah Stok', color: 'border-green-400 bg-green-50 text-green-700' },
                  { value: 'adjustment_out', label: 'Kurangi Stok', color: 'border-red-400 bg-red-50 text-red-700' },
                ].map(opt => (
                  <button key={opt.value} onClick={() => setForm(p => ({ ...p, movement_type: opt.value }))}
                    className={`py-2 px-3 rounded-lg border text-sm font-medium transition-colors ${form.movement_type === opt.value ? opt.color : 'border-gray-200 text-gray-600 hover:border-gray-300'}`}>
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="label">Jumlah *</label>
              <input type="number" className="input" min="0.1" step="0.1" placeholder="0"
                value={form.qty} onChange={e => setForm(p => ({ ...p, qty: e.target.value }))} />
            </div>

            <div>
              <label className="label">Alasan</label>
              <select className="input" value={form.reason} onChange={e => setForm(p => ({ ...p, reason: e.target.value }))}>
                <option value="">Pilih alasan...</option>
                <option value="Rusak">Rusak</option>
                <option value="Hilang">Hilang</option>
                <option value="Koreksi">Koreksi</option>
                <option value="Stok fisik">Stok fisik</option>
                <option value="Lainnya">Lainnya</option>
              </select>
            </div>

            <div className="flex gap-2 pt-2">
              <button onClick={() => setModal(false)} className="btn-secondary flex-1 justify-center">Batal</button>
              <button onClick={handleAdjust} disabled={saving} className="btn-primary flex-1 justify-center">
                {saving ? 'Menyimpan...' : 'Simpan'}
              </button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
