import { useEffect, useMemo, useState } from 'react';
import {
  Plus, Search, RefreshCw, Pencil, Trash2, AlertCircle, Loader2,
  Phone, Mail, MapPin, Hash, Building2, ChevronLeft, ChevronRight, X,
} from 'lucide-react';
import { useFinanceStore, Supplier } from '../../store/finance';
import { Modal, ModalBody } from '../../components/ui/Modal';

const PAGE_SIZE = 25;

export default function Suppliers() {
  const {
    suppliers,
    loading,
    error,
    fetchSuppliers,
    createSupplier,
    updateSupplier,
    deleteSupplier,
  } = useFinanceStore();

  const [search, setSearch] = useState('');
  const [status, setStatus] = useState<'all' | 'active' | 'inactive'>('all');
  const [page, setPage] = useState(0);
  const [editor, setEditor] = useState<Supplier | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState<Supplier | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    fetchSuppliers({ status: status === 'all' ? undefined : status });
  }, [status, fetchSuppliers]);

  const filtered = useMemo(() => {
    if (!search.trim()) return suppliers;
    const needle = search.toLowerCase();
    return suppliers.filter((s) =>
      (s.name || '').toLowerCase().includes(needle) ||
      (s.code || '').toLowerCase().includes(needle) ||
      (s.contact_person || '').toLowerCase().includes(needle) ||
      (s.email || '').toLowerCase().includes(needle)
    );
  }, [suppliers, search]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageRows = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  const saveSupplier = async (data: Partial<Supplier>) => {
    setBusy(true);
    if (editor && !isCreating) {
      const r = await updateSupplier(editor.uid, data);
      setBusy(false);
      if (r) { setEditor(null); setIsCreating(false); }
      return r;
    }
    const r = await createSupplier(data);
    setBusy(false);
    if (r) { setEditor(null); setIsCreating(false); }
    return r;
  };

  const onDelete = async (s: Supplier) => {
    setBusy(true);
    const ok = await deleteSupplier(s.uid);
    setBusy(false);
    if (ok) setConfirmDelete(null);
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Suppliers</h1>
          <p className="text-text-muted mt-1 text-lg">Vendor registry — shared with inventory.</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => fetchSuppliers({ status: status === 'all' ? undefined : status })}
            className="flex items-center gap-2 px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
          >
            <RefreshCw size={16} /> Refresh
          </button>
          <button
            onClick={() => { setIsCreating(true); setEditor({} as Supplier); }}
            className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
          >
            <Plus size={18} /> New Supplier
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="relative sm:col-span-2">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search name, code, contact…"
              value={search}
              onChange={(e) => { setSearch(e.target.value); setPage(0); }}
              className="w-full pl-9 pr-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>
          <select
            value={status}
            onChange={(e) => { setStatus(e.target.value as any); setPage(0); }}
            className="px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
          >
            <option value="all">All statuses</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
          </select>
        </div>
        <p className="text-[0.65rem] mt-3 text-text-muted">
          {loading ? 'Loading…' : `${filtered.length} supplier${filtered.length === 1 ? '' : 's'}`}
        </p>
      </div>

      {error && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
        </div>
      )}

      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/80 border-b border-border">
              <tr>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Name</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Code</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Contact</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Email</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Phone</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((s) => (
                  <tr key={s.uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md bg-primary/10 text-primary">
                          <Building2 size={14} />
                        </div>
                        <p className="text-[0.85rem] font-semibold text-text">{s.name}</p>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-[0.75rem] font-mono text-text-muted">{s.code || '—'}</td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary">{s.contact_person || '—'}</td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-muted">{s.email || '—'}</td>
                    <td className="px-6 py-4 text-[0.85rem] font-mono text-text-muted">{s.phone || '—'}</td>
                    <td className="px-6 py-4">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${
                        s.is_active ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300'
                                    : 'bg-muted text-text-muted border-border'
                      }`}>
                        {s.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-1">
                        <button
                          onClick={() => { setIsCreating(false); setEditor(s); }}
                          className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all"
                          title="Edit supplier"
                          aria-label="Edit supplier"
                        >
                          <Pencil size={16} />
                        </button>
                        <button
                          onClick={() => setConfirmDelete(s)}
                          className="p-2 rounded-lg hover:bg-red-500 hover:text-white text-text-muted transition-all"
                          title="Delete supplier"
                          aria-label="Delete supplier"
                        >
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={7} className="px-6 py-10 text-center text-text-muted text-sm">No suppliers match the current filters.</td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="px-6 py-4 border-t border-border bg-muted/30 flex items-center justify-between">
          <span className="text-[0.7rem] font-bold text-text-muted">Page {page + 1} of {totalPages}</span>
          <div className="inline-flex items-center gap-2">
            <button disabled={page === 0} onClick={() => setPage((p) => Math.max(0, p - 1))} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              <ChevronLeft size={14} /> Prev
            </button>
            <button disabled={page + 1 >= totalPages} onClick={() => setPage((p) => p + 1)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              Next <ChevronRight size={14} />
            </button>
          </div>
        </div>
      </div>

      {editor && (
        <SupplierEditor
          initial={editor}
          isCreating={isCreating}
          busy={busy}
          onSave={saveSupplier}
          onClose={() => { setEditor(null); setIsCreating(false); }}
        />
      )}

      {confirmDelete && (
        <Modal
          open={true}
          onClose={() => setConfirmDelete(null)}
          title="Delete supplier?"
          icon={Trash2}
          maxWidth="max-w-sm"
          footer={
            <>
              <button onClick={() => setConfirmDelete(null)} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
              <button onClick={() => onDelete(confirmDelete)} disabled={busy} className="px-4 py-2 rounded-xl bg-red-500 text-white text-sm font-bold hover:bg-red-600 transition-all">
                {busy ? <Loader2 size={14} className="animate-spin" /> : 'Delete'}
              </button>
            </>
          }
        >
          <ModalBody>
            <p className="text-sm text-text-muted">
              Soft-deletes <strong>{confirmDelete.name}</strong>. Existing purchase orders referencing this vendor remain intact.
            </p>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}

function SupplierEditor({
  initial, isCreating, busy, onSave, onClose,
}: {
  initial: Supplier;
  isCreating: boolean;
  busy: boolean;
  onSave: (data: Partial<Supplier>) => Promise<unknown>;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial.name || '');
  const [code, setCode] = useState(initial.code || '');
  const [contactPerson, setContactPerson] = useState(initial.contact_person || '');
  const [email, setEmail] = useState(initial.email || '');
  const [phone, setPhone] = useState(initial.phone || '');
  const [address, setAddress] = useState(initial.address || '');
  const [city, setCity] = useState(initial.city || '');
  const [country, setCountry] = useState(initial.country || 'Zimbabwe');
  const [taxId, setTaxId] = useState(initial.tax_id || '');
  const [notes, setNotes] = useState(initial.notes || '');
  const [active, setActive] = useState(initial.is_active !== 0);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    await onSave({
      name: name.trim(),
      code: code.trim() || null,
      contact_person: contactPerson.trim() || null,
      email: email.trim() || null,
      phone: phone.trim() || null,
      address: address.trim() || null,
      city: city.trim() || null,
      country: country.trim() || 'Zimbabwe',
      tax_id: taxId.trim() || null,
      notes: notes.trim() || null,
      is_active: active ? 1 : 0,
    });
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={isCreating ? 'New supplier' : `Edit ${initial.name}`}
      icon={Building2}
      maxWidth="max-w-2xl"
      footer={
        <>
          <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
          <button type="submit" form="supplier-form" disabled={busy || !name.trim()} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark disabled:opacity-40 transition-all">
            {busy && <Loader2 size={14} className="animate-spin" />}
            <span>{isCreating ? 'Create' : 'Save'}</span>
          </button>
        </>
      }
    >
      <ModalBody>
        <form id="supplier-form" onSubmit={submit}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <Field icon={Building2} label="Name *" value={name} onChange={setName} required />
            <Field icon={Hash} label="Code" value={code} onChange={setCode} />
            <Field icon={Building2} label="Contact person" value={contactPerson} onChange={setContactPerson} />
            <Field icon={Mail} label="Email" value={email} onChange={setEmail} type="email" />
            <Field icon={Phone} label="Phone" value={phone} onChange={setPhone} />
            <Field icon={MapPin} label="Tax ID" value={taxId} onChange={setTaxId} />
            <Field icon={MapPin} label="Address" value={address} onChange={setAddress} wide />
            <Field icon={MapPin} label="City" value={city} onChange={setCity} />
            <Field icon={MapPin} label="Country" value={country} onChange={setCountry} />
          </div>
          <label className="block mt-3">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Notes</span>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={3}
              className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </label>
          <label className="flex items-center gap-2 mt-3 text-sm">
            <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} className="accent-primary" />
            <span>Active</span>
          </label>
        </form>
      </ModalBody>
    </Modal>
  );
}

function Field({
  icon: Icon, label, value, onChange, type = 'text', required, wide,
}: {
  icon: typeof Hash; label: string; value: string; onChange: (v: string) => void;
  type?: string; required?: boolean; wide?: boolean;
}) {
  return (
    <label className={`block ${wide ? 'md:col-span-2' : ''}`}>
      <span className="text-xs font-bold uppercase tracking-wider text-text-muted flex items-center gap-1">
        <Icon size={12} /> {label}
      </span>
      <input
        type={type}
        required={required}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
      />
    </label>
  );
}
