import React, { useState, useMemo } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { Supplier } from '../types';
import { PaginationControl } from '../components/PaginationControl';
import { Truck, Plus, Search, Edit2, Trash2, Phone, MapPin, Building2, MessageSquare, AlertCircle, CheckCircle2, FileText } from 'lucide-react';
import { requiredRule, phoneRule, validateForm, isInvalid } from '../rules';

export const SuppliersPage: React.FC = () => {
  const { db, addSupplier, updateSupplier, deleteSupplier } = useStore();

  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 8;

  // Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingSupplier, setEditingSupplier] = useState<Supplier | null>(null);

  // Form Fields
  const [name, setName] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [notes, setNotes] = useState('');
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);

  const suppliers = db.suppliers || [];

  // Filtered Suppliers
  const filteredSuppliers = useMemo(() => {
    if (!searchTerm.trim()) return suppliers;
    const q = searchTerm.toLowerCase().trim();
    return suppliers.filter(s =>
      s.name.toLowerCase().includes(q) ||
      (s.companyName && s.companyName.toLowerCase().includes(q)) ||
      s.phone.includes(q) ||
      s.address.toLowerCase().includes(q) ||
      (s.notes && s.notes.toLowerCase().includes(q))
    );
  }, [suppliers, searchTerm]);

  // Pagination
  const totalPages = Math.ceil(filteredSuppliers.length / itemsPerPage) || 1;
  const paginatedSuppliers = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage;
    return filteredSuppliers.slice(start, start + itemsPerPage);
  }, [filteredSuppliers, currentPage]);

  const handleOpenAddModal = () => {
    setEditingSupplier(null);
    setName('');
    setCompanyName('');
    setPhone('');
    setAddress('');
    setNotes('');
    setFieldErrors({});
    setFormError(null);
    setIsModalOpen(true);
  };

  const handleOpenEditModal = (supplier: Supplier) => {
    setEditingSupplier(supplier);
    setName(supplier.name);
    setCompanyName(supplier.companyName || '');
    setPhone(supplier.phone);
    setAddress(supplier.address);
    setNotes(supplier.notes || '');
    setFieldErrors({});
    setFormError(null);
    setIsModalOpen(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);

    const { isValid, errors } = validateForm(
      { name, phone, address },
      {
        name: [requiredRule('Nama supplier / kontak utama wajib diisi!')],
        phone: [requiredRule('Nomor telepon / WA wajib diisi!'), phoneRule()],
        address: [requiredRule('Alamat lengkap kantor / gudang wajib diisi!')]
      }
    );

    if (!isValid) {
      setFieldErrors(errors as Record<string, string>);
      setFormError('Harap perbaiki kolom yang tidak valid di bawah ini!');
      return;
    }

    setFieldErrors({});

    if (editingSupplier) {
      updateSupplier(editingSupplier.id, {
        name: name.trim(),
        companyName: companyName.trim() || undefined,
        phone: phone.trim(),
        address: address.trim(),
        notes: notes.trim() || undefined
      });
      Swal.fire({
        icon: 'success',
        title: 'Supplier Diperbarui!',
        text: `Data ${name} berhasil diperbarui.`,
        timer: 1500,
        showConfirmButton: false
      });
    } else {
      addSupplier({
        name: name.trim(),
        companyName: companyName.trim() || undefined,
        phone: phone.trim(),
        address: address.trim(),
        notes: notes.trim() || undefined
      });
      Swal.fire({
        icon: 'success',
        title: 'Supplier Didaftarkan!',
        text: `Supplier baru ${name} berhasil ditambahkan.`,
        timer: 1500,
        showConfirmButton: false
      });
    }

    setIsModalOpen(false);
  };

  const handleDelete = (supplier: Supplier) => {
    // Check if supplier has inbound records
    const linkedInbound = (db.inboundRecords || []).filter(r =>
      r.supplierName.toLowerCase() === supplier.name.toLowerCase()
    );

    Swal.fire({
      title: 'Hapus Supplier?',
      html: `
        <div class="text-left text-xs text-slate-600 space-y-2">
          <p>Apakah Anda yakin ingin menghapus supplier <b>"${supplier.name}"</b>?</p>
          ${linkedInbound.length > 0 ? `<div class="p-2.5 bg-amber-50 border border-amber-200 rounded-lg text-amber-800 font-semibold">⚠️ Supplier ini tercatat pada <b>${linkedInbound.length} transaksi penerimaan barang</b>. Riwayat barang masuk tidak akan hilang, tapi data supplier tidak lagi di master.</div>` : ''}
        </div>
      `,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#e11d48',
      cancelButtonColor: '#64748b',
      confirmButtonText: 'Ya, Hapus Supplier',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        deleteSupplier(supplier.id);
        Swal.fire({
          icon: 'success',
          title: 'Supplier Dihapus',
          text: `Data supplier ${supplier.name} telah dihapus.`,
          timer: 1500,
          showConfirmButton: false
        });
      }
    });
  };

  // Format WhatsApp Link
  const getWaLink = (rawPhone: string) => {
    let clean = rawPhone.replace(/\D/g, '');
    if (clean.startsWith('0')) clean = '62' + clean.slice(1);
    return `https://wa.me/${clean}`;
  };

  return (
    <div className="space-y-6">
      
      {/* Top Banner */}
      <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-2xs flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2.5">
            <div className="p-2 bg-emerald-100 text-emerald-800 rounded-xl">
              <Truck className="w-6 h-6 text-emerald-700" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-slate-900">Master Supplier & Distributor</h2>
              <p className="text-xs text-slate-500 mt-0.5">
                Kelola daftar pemasok, distributor, dan agen sembako untuk mempermudah penerimaan barang.
              </p>
            </div>
          </div>
        </div>

        <button
          onClick={handleOpenAddModal}
          className="px-5 py-2.5 bg-emerald-700 hover:bg-emerald-800 text-white font-bold text-xs rounded-xl shadow-md transition flex items-center justify-center gap-2 active:scale-95 shrink-0"
        >
          <Plus className="w-4 h-4" />
          <span>Tambah Supplier Baru</span>
        </button>
      </div>

      {/* Summary Stat Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-4">
          <div className="p-3 bg-emerald-50 text-emerald-700 rounded-xl">
            <Truck className="w-6 h-6" />
          </div>
          <div>
            <p className="text-xs font-semibold text-slate-500">Total Supplier Terdaftar</p>
            <p className="text-2xl font-black text-slate-900">{suppliers.length} <span className="text-xs font-normal text-slate-500">Pemasok</span></p>
          </div>
        </div>

        <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-4">
          <div className="p-3 bg-blue-50 text-blue-700 rounded-xl">
            <Building2 className="w-6 h-6" />
          </div>
          <div>
            <p className="text-xs font-semibold text-slate-500">Perusahaan / Agen Resmi</p>
            <p className="text-2xl font-black text-slate-900">
              {suppliers.filter(s => s.companyName).length} <span className="text-xs font-normal text-slate-500">Distributor</span>
            </p>
          </div>
        </div>

        <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-4 sm:col-span-2 lg:col-span-1">
          <div className="p-3 bg-teal-50 text-teal-700 rounded-xl">
            <FileText className="w-6 h-6" />
          </div>
          <div>
            <p className="text-xs font-semibold text-slate-500">Total Penerimaan Stok</p>
            <p className="text-2xl font-black text-slate-900">
              {(db.inboundRecords || []).length} <span className="text-xs font-normal text-slate-500">Faktur Masuk</span>
            </p>
          </div>
        </div>
      </div>

      {/* Search Bar */}
      <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => {
              setSearchTerm(e.target.value);
              setCurrentPage(1);
            }}
            placeholder="Cari berdasarkan nama supplier, PT/CV, nomor HP, atau alamat..."
            className="w-full pl-10 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-medium focus:outline-none focus:ring-2 focus:ring-emerald-500"
          />
        </div>
        {searchTerm && (
          <button
            onClick={() => setSearchTerm('')}
            className="px-3 py-2 text-xs font-bold text-slate-600 hover:bg-slate-100 rounded-xl transition"
          >
            Reset
          </button>
        )}
      </div>

      {/* Suppliers Table / List */}
      <div className="bg-white border border-slate-200 rounded-2xl shadow-2xs overflow-hidden">
        <div className="p-4 border-b border-slate-100 flex items-center justify-between">
          <h3 className="font-bold text-sm text-slate-800 flex items-center gap-2">
            <Truck className="w-4 h-4 text-emerald-600" />
            <span>Daftar Supplier ({filteredSuppliers.length})</span>
          </h3>
        </div>

        {filteredSuppliers.length === 0 ? (
          <div className="p-12 text-center space-y-3">
            <div className="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto text-slate-400">
              <Truck className="w-6 h-6" />
            </div>
            <p className="text-sm font-bold text-slate-700">Belum Ada Data Supplier</p>
            <p className="text-xs text-slate-500 max-w-sm mx-auto">
              {searchTerm ? 'Tidak ada supplier yang sesuai dengan kata kunci pencarian.' : 'Tambahkan data distributor atau agen supplier sembako Anda untuk mempermudah pencatatan stok.'}
            </p>
            {!searchTerm && (
              <button
                onClick={handleOpenAddModal}
                className="mt-2 px-4 py-2 bg-emerald-700 hover:bg-emerald-800 text-white font-bold text-xs rounded-xl transition inline-flex items-center gap-1.5"
              >
                <Plus className="w-4 h-4" /> Tambah Supplier Sekarang
              </button>
            )}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-slate-50 border-b border-slate-200 text-[11px] font-extrabold text-slate-500 uppercase tracking-wider">
                  <th className="p-3.5 pl-5">Nama Supplier & Perusahaan</th>
                  <th className="p-3.5">Kontak / WhatsApp</th>
                  <th className="p-3.5">Alamat Lengkap</th>
                  <th className="p-3.5">Catatan / Komoditas</th>
                  <th className="p-3.5 text-right pr-5">Aksi</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 text-xs">
                {paginatedSuppliers.map((supplier) => (
                  <tr key={supplier.id} className="hover:bg-slate-50/80 transition">
                    <td className="p-3.5 pl-5">
                      <div className="font-bold text-slate-900 text-sm">{supplier.name}</div>
                      {supplier.companyName && (
                        <div className="text-[11px] text-slate-500 flex items-center gap-1 mt-0.5 font-medium">
                          <Building2 className="w-3 h-3 text-slate-400 shrink-0" />
                          <span>{supplier.companyName}</span>
                        </div>
                      )}
                    </td>

                    <td className="p-3.5">
                      <div className="flex items-center gap-2">
                        <span className="font-mono font-semibold text-slate-800">{supplier.phone}</span>
                        <a
                          href={getWaLink(supplier.phone)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="p-1.5 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 rounded-lg transition"
                          title="Chat via WhatsApp"
                        >
                          <MessageSquare className="w-3.5 h-3.5 text-emerald-600" />
                        </a>
                      </div>
                    </td>

                    <td className="p-3.5 max-w-xs">
                      <div className="text-slate-600 flex items-start gap-1.5 line-clamp-2">
                        <MapPin className="w-3.5 h-3.5 text-slate-400 shrink-0 mt-0.5" />
                        <span>{supplier.address}</span>
                      </div>
                    </td>

                    <td className="p-3.5 max-w-xs">
                      <span className="text-slate-500 text-[11px] italic">
                        {supplier.notes || '-'}
                      </span>
                    </td>

                    <td className="p-3.5 pr-5 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        <button
                          onClick={() => handleOpenEditModal(supplier)}
                          className="p-1.5 text-slate-600 hover:text-emerald-700 hover:bg-emerald-50 rounded-lg transition"
                          title="Edit Supplier"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(supplier)}
                          className="p-1.5 text-slate-600 hover:text-rose-700 hover:bg-rose-50 rounded-lg transition"
                          title="Hapus Supplier"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Pagination */}
        {filteredSuppliers.length > 0 && (
          <div className="p-4 border-t border-slate-100">
            <PaginationControl
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </div>

      {/* MODAL: ADD / EDIT SUPPLIER */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-xs p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg border border-slate-100 overflow-hidden my-auto animate-in fade-in zoom-in-95 duration-150">
            
            {/* Modal Header */}
            <div className="bg-emerald-800 text-white px-6 py-4 flex items-center justify-between">
              <div className="flex items-center gap-2.5">
                <Truck className="w-5 h-5 text-emerald-300" />
                <h3 className="font-bold text-base">
                  {editingSupplier ? 'Edit Data Supplier' : 'Tambah Supplier Baru'}
                </h3>
              </div>
              <button
                onClick={() => setIsModalOpen(false)}
                className="text-emerald-200 hover:text-white text-lg font-bold p-1 rounded-lg hover:bg-emerald-700/50"
              >
                &times;
              </button>
            </div>

            {/* Modal Form */}
            <form onSubmit={handleSubmit} noValidate className="p-6 space-y-4">
              
              {formError && (
                <div className="p-3 bg-rose-50 border border-rose-200 rounded-xl flex items-center gap-2 text-rose-800 text-xs font-semibold">
                  <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
                  <span>{formError}</span>
                </div>
              )}

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Nama Supplier / Kontak Utama <span className="text-rose-500">*</span>
                </label>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => {
                    setName(e.target.value);
                    if (fieldErrors.name) setFieldErrors(prev => ({ ...prev, name: '' }));
                  }}
                  placeholder="cth: Pak Budi / Distributor Mayora Indah"
                  className={`w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-emerald-500 ${isInvalid(fieldErrors.name)}`}
                />
                {fieldErrors.name && (
                  <span className="invalid-feedback">
                    <AlertCircle className="w-3 h-3" /> {fieldErrors.name}
                  </span>
                )}
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Nama Perusahaan / PT / CV / Agen (Opsional)
                </label>
                <input
                  type="text"
                  value={companyName}
                  onChange={(e) => setCompanyName(e.target.value)}
                  placeholder="cth: PT Distribusi Sembako Nusantara"
                  className="w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-emerald-500"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Nomor HP / WhatsApp <span className="text-rose-500">*</span>
                </label>
                <div className="relative">
                  <Phone className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    value={phone}
                    onChange={(e) => {
                      setPhone(e.target.value);
                      if (fieldErrors.phone) setFieldErrors(prev => ({ ...prev, phone: '' }));
                    }}
                    placeholder="cth: 081234567890"
                    className={`w-full pl-9 pr-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-mono font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-emerald-500 ${isInvalid(fieldErrors.phone)}`}
                  />
                </div>
                {fieldErrors.phone && (
                  <span className="invalid-feedback">
                    <AlertCircle className="w-3 h-3" /> {fieldErrors.phone}
                  </span>
                )}
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Alamat Lengkap Kantor / Gudang <span className="text-rose-500">*</span>
                </label>
                <textarea
                  value={address}
                  onChange={(e) => {
                    setAddress(e.target.value);
                    if (fieldErrors.address) setFieldErrors(prev => ({ ...prev, address: '' }));
                  }}
                  rows={2}
                  placeholder="cth: Jl. Raya Industri No. 12, Pulo Gadung, Jakarta Timur"
                  className={`w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-emerald-500 resize-none ${isInvalid(fieldErrors.address)}`}
                />
                {fieldErrors.address && (
                  <span className="invalid-feedback">
                    <AlertCircle className="w-3 h-3" /> {fieldErrors.address}
                  </span>
                )}
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Catatan / Komoditas Barang (Opsional)
                </label>
                <input
                  type="text"
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  placeholder="cth: Pemasok beras Sania, Fortune & minyak Bimoli"
                  className="w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-emerald-500"
                />
              </div>

              {/* Modal Footer */}
              <div className="pt-4 border-t border-slate-100 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs rounded-xl transition"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-emerald-700 hover:bg-emerald-800 text-white font-bold text-xs rounded-xl shadow-md transition flex items-center gap-1.5"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  <span>{editingSupplier ? 'Simpan Perubahan' : 'Tambah Supplier'}</span>
                </button>
              </div>

            </form>
          </div>
        </div>
      )}

    </div>
  );
};
