'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch, adminApiUploadFile } from '@/lib/api';
import { useToast } from '@/lib/toast';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type ProductRow = {
  id: number; sku: string; name: string; stockQty: number; shelfLocation: string | null; lowStockAlert: number;
  inventoryLogs: { createdAt: string; checkedBy: { name: string } | null }[];
};

export default function InventoryPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [products, setProducts] = useState<ProductRow[]>([]);
  const [lowStockCount, setLowStockCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [countTarget, setCountTarget] = useState<ProductRow | null>(null);
  const [countValue, setCountValue] = useState('');
  const [countPhoto, setCountPhoto] = useState<File | null>(null);
  const [countPhotoPreview, setCountPhotoPreview] = useState<string | null>(null);
  const [uploadingPhoto, setUploadingPhoto] = useState(false);
  const [poTarget, setPoTarget] = useState<ProductRow | null>(null);
  const [supplier, setSupplier] = useState('');
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/inventory', accessToken, appSecretProof);
      setProducts(d.products || []);
      setLowStockCount(d.lowStockCount || 0);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function submitCount(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !countTarget) return;
    setSaving(true);
    try {
      let photoUrl: string | undefined;
      if (countPhoto) {
        setUploadingPhoto(true);
        try {
          const uploaded = await adminApiUploadFile('/admin/inventory/upload-photo', accessToken, appSecretProof, countPhoto);
          photoUrl = uploaded.url;
        } catch {
          show('error', 'Photo upload failed — saving the count without it.');
        } finally {
          setUploadingPhoto(false);
        }
      }
      await adminApiFetch('/admin/inventory/count', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ productId: countTarget.id, quantity: Number(countValue), photoUrl }),
      });
      show('success', `${countTarget.name} count updated to ${countValue}.`);
      setCountTarget(null);
      setCountValue('');
      setCountPhoto(null);
      setCountPhotoPreview(null);
      load();
    } catch { show('error', 'Could not update the count.'); }
    finally { setSaving(false); }
  }

  function onPhotoSelected(file: File | null) {
    setCountPhoto(file);
    if (countPhotoPreview) URL.revokeObjectURL(countPhotoPreview);
    setCountPhotoPreview(file ? URL.createObjectURL(file) : null);
  }

  async function submitPO(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !poTarget || !supplier.trim()) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/inventory/purchase-orders', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ supplier, itemsJson: [{ productId: poTarget.id, sku: poTarget.sku, qty: 20 }] }),
      });
      show('success', `Purchase order sent to ${supplier}.`);
      setPoTarget(null);
      setSupplier('');
    } catch { show('error', 'Could not create the purchase order.'); }
    finally { setSaving(false); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-4">
      <div className="flex justify-between">
        <h1 className="text-xl font-bold">Inventory &bull; Ubungo Warehouse</h1>
        <span className="border px-3 py-1.5 rounded-full text-xs">Low Stock Alert {lowStockCount}</span>
      </div>

      {loading ? <TableSkeleton rows={5} cols={5} /> : (
        <div className="bg-white rounded-xl border border-brand-border overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg"><tr>
              <th className="p-3 text-left">Product &bull; SKU</th><th className="p-3 text-left">Quantity &bull; Shelf</th>
              <th className="p-3 text-left">Low Threshold</th><th className="p-3 text-left">Last Check</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {products.map((p) => {
                const low = p.stockQty <= p.lowStockAlert;
                const lastLog = p.inventoryLogs[0];
                return (
                  <tr key={p.id} className={`border-t border-brand-border transition-colors ${low ? 'bg-red-50 hover:bg-red-100' : 'hover:bg-brand-bg'}`}>
                    <td className="p-3">{p.name} &bull; {p.sku}</td>
                    <td className={`p-3 font-bold ${low ? 'text-brand-live' : ''}`}>{p.stockQty} units &bull; {p.shelfLocation || '—'}</td>
                    <td className="p-3">{p.lowStockAlert}</td>
                    <td className="p-3 text-gray-500">{lastLog ? `${new Date(lastLog.createdAt).toLocaleDateString()} • ${lastLog.checkedBy?.name || '—'}` : 'Never'}</td>
                    <td className="p-3 space-x-1">
                      <button onClick={() => { setCountTarget(p); setCountValue(String(p.stockQty)); }} className="border px-2 py-1 rounded text-[10px] transition-colors hover:bg-brand-bg">Update Count</button>
                      {low && <button onClick={() => setPoTarget(p)} className="bg-brand-live text-white px-2 py-1 rounded text-[10px] transition-transform hover:scale-105">Create PO</button>}
                    </td>
                  </tr>
                );
              })}
              {products.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-gray-400">No products yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
      <p className="text-[11px] text-gray-400">Attach a photo when updating a count for a dated proof-of-stock record.</p>

      {countTarget && (
        <Modal title={`Update count — ${countTarget.name}`} onClose={() => { setCountTarget(null); onPhotoSelected(null); }}>
          <form onSubmit={submitCount} className="space-y-3">
            <div>
              <label className="text-xs font-medium text-gray-600">New counted quantity</label>
              <input required type="number" min={0} autoFocus value={countValue} onChange={(e) => setCountValue(e.target.value)}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red" />
            </div>
            <div>
              <label className="text-xs font-medium text-gray-600">Photo proof (optional)</label>
              <input type="file" accept="image/*" onChange={(e) => onPhotoSelected(e.target.files?.[0] || null)}
                className="mt-1 w-full text-xs" />
              {countPhotoPreview && (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={countPhotoPreview} alt="Preview" className="mt-2 h-24 rounded-lg border border-brand-border object-cover animate-fadeIn" />
              )}
            </div>
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {uploadingPhoto ? 'Uploading photo…' : saving ? 'Saving…' : 'Save Count'}
            </button>
          </form>
        </Modal>
      )}

      {poTarget && (
        <Modal title={`Create purchase order — ${poTarget.name}`} onClose={() => setPoTarget(null)}>
          <form onSubmit={submitPO} className="space-y-3">
            <div>
              <label className="text-xs font-medium text-gray-600">Supplier name</label>
              <input required autoFocus value={supplier} onChange={(e) => setSupplier(e.target.value)}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red" placeholder="Default Supplier" />
            </div>
            <p className="text-[11px] text-gray-400">Orders 20 units of {poTarget.sku} by default — quantity editing per-line is a future enhancement.</p>
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {saving ? 'Creating…' : 'Create Purchase Order'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
