import { useState, useMemo } from 'react'
import { useApp } from '../context/AppContext'
import { formatRupiah } from '../utils/formatRupiah'
import { terbilang } from '../utils/terbilang'
import { formatTanggalIndo } from '../utils/generateNomorKW'
import PageHeader from '../components/PageHeader'
import Modal from '../components/Modal'
import { Save, Eye, RotateCcw, Calculator, ChevronDown, Plus, Trash2, Warehouse } from 'lucide-react'
import ConfirmDialog from '../components/ConfirmDialog'

const UKURAN_CONTAINER = ["20'", "40'", 'Flat Rack']

const newContainer = () => ({
  id: Date.now() + Math.random(),
  nomorContainer: '',
  ukuran: "20'",
  kapal: '',
  voyage: '',
  overrideLolo: '',
})

const initialForm = {
  klienId: '',
  consignee: '',
  alamat: '',
  npwp: '',
  catatan: '',
  containers: [newContainer()],
}

// ─── Reusable UI ─────────────────────────────────────────────────────────────
function Field({ label, required, children, hint }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <label style={{ fontSize: 12.5, fontWeight: 600, color: '#374151' }}>
        {label}{required && <span style={{ color: '#ef4444', marginLeft: 2 }}>*</span>}
      </label>
      {children}
      {hint && <span style={{ fontSize: 11, color: '#9ca3af' }}>{hint}</span>}
    </div>
  )
}

function Input({ value, onChange, placeholder, type = 'text', disabled }) {
  return (
    <input
      type={type} value={value} onChange={onChange}
      placeholder={placeholder} disabled={disabled}
      style={{
        padding: '9px 12px', borderRadius: 8, fontSize: 13.5,
        border: '1.5px solid #e2e8f0', outline: 'none',
        background: disabled ? '#f8fafc' : 'white',
        color: disabled ? '#94a3b8' : '#1a2332',
        transition: 'border-color 0.15s',
        fontFamily: 'inherit', width: '100%', boxSizing: 'border-box',
      }}
      onFocus={e => { if (!disabled) e.target.style.borderColor = '#10b981' }}
      onBlur={e => { e.target.style.borderColor = '#e2e8f0' }}
    />
  )
}

function Select({ value, onChange, options }) {
  return (
    <div style={{ position: 'relative' }}>
      <select
        value={value} onChange={onChange}
        style={{
          padding: '9px 36px 9px 12px', borderRadius: 8, fontSize: 13.5,
          border: '1.5px solid #e2e8f0', outline: 'none',
          background: 'white', color: '#1a2332',
          width: '100%', boxSizing: 'border-box',
          cursor: 'pointer', appearance: 'none', fontFamily: 'inherit',
        }}
        onFocus={e => { e.target.style.borderColor = '#10b981' }}
        onBlur={e => { e.target.style.borderColor = '#e2e8f0' }}
      >
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <ChevronDown size={14} color="#94a3b8" style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
    </div>
  )
}

function SectionTitle({ children }) {
  return (
    <div style={{
      fontSize: 11, fontWeight: 700, letterSpacing: '0.1em',
      textTransform: 'uppercase', color: '#94a3b8',
      borderBottom: '1px solid #f1f5f9', paddingBottom: 8, marginBottom: 4,
    }}>
      {children}
    </div>
  )
}

// ─── Hitung per container ─────────────────────────────────────────────────────
function hitungPerContainer(c, tarifData) {
  let tarifLolo = 0
  if (c.ukuran === "20'")      tarifLolo = tarifData.paketLoloTrucking20 ?? 0
  else if (c.ukuran === "40'") tarifLolo = tarifData.paketLoloTrucking40 ?? 0
  else                         tarifLolo = tarifData.paketLoloTrucking40 ?? 0 // FR pakai tarif 40' sbg default

  if (c.overrideLolo !== '') tarifLolo = parseFloat(c.overrideLolo) || tarifLolo

  return {
    baris: [{ label: 'Paket Lolo dan Trucking', tarif: tarifLolo, jumlah: tarifLolo }],
    subTotal: tarifLolo,
    ukuran: c.ukuran,
    nomorContainer: c.nomorContainer,
    kapal: c.kapal,
    voyage: c.voyage,
  }
}

// ─── Preview Invoice ──────────────────────────────────────────────────────────
function PreviewInvoice({ data }) {
  if (!data) return null
  const { form, kalkulasi, nomorKW, tanggalInvoice } = data

  return (
    <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 13 }}>
      {/* Header */}
      <div style={{ textAlign: 'center', marginBottom: 16, paddingBottom: 14, borderBottom: '2px solid #0f1f3d' }}>
        <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: '0.05em', color: '#0f1f3d' }}>KWITANSI</div>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#374151' }}>
          GUDANG UMUM — {form.containers.length} CONTAINER
        </div>
        <div style={{ fontSize: 12, color: '#64748b' }}>No. : {nomorKW}</div>
      </div>

      {/* Info consignee */}
      <div style={{ display: 'grid', gridTemplateColumns: '110px 1fr', gap: '5px 8px', marginBottom: 16 }}>
        {[
          ['Consignee', form.consignee],
          ['Alamat', form.alamat],
          ['NPWP', form.npwp],
        ].filter(([, v]) => v).map(([k, v]) => (
          <>
            <div key={k + '-k'} style={{ fontWeight: 600, color: '#374151' }}>{k}</div>
            <div key={k + '-v'} style={{ color: '#1a2332' }}>: {v}</div>
          </>
        ))}
      </div>

      {/* Tabel biaya */}
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, marginBottom: 8 }}>
        <thead>
          <tr style={{ background: '#0f1f3d', color: 'white' }}>
            {['Uraian Biaya', "20'", "40'", 'Kapal / Voy', 'Tarif (Rp)', 'Jumlah'].map(h => (
              <th key={h} style={{ padding: '6px 10px', textAlign: ['Jumlah', 'Tarif (Rp)'].includes(h) ? 'right' : 'left', fontWeight: 600, fontSize: 11 }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {kalkulasi.perContainer.map((pc, idx) => (
            <tr key={idx} style={{ borderBottom: '1px solid #f1f5f9', background: idx % 2 === 0 ? 'white' : '#fafafa' }}>
              <td style={{ padding: '7px 10px' }}>Paket Lolo dan Trucking</td>
              <td style={{ padding: '7px 10px', textAlign: 'center', color: '#64748b' }}>{pc.ukuran === "20'" ? 1 : ''}</td>
              <td style={{ padding: '7px 10px', textAlign: 'center', color: '#64748b' }}>{pc.ukuran !== "20'" ? 1 : ''}</td>
              <td style={{ padding: '7px 10px', color: '#64748b', fontSize: 12 }}>
                {[form.containers[idx]?.kapal, form.containers[idx]?.voyage].filter(Boolean).join(' / ')}
              </td>
              <td style={{ padding: '7px 10px', textAlign: 'right', color: '#64748b' }}>{formatRupiah(pc.baris[0].tarif, false)}</td>
              <td style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 500 }}>{formatRupiah(pc.subTotal, false)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* Totals */}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <tbody>
          <tr style={{ background: '#f8fafc' }}>
            <td colSpan={5} style={{ padding: '7px 10px', fontWeight: 700, color: '#0f1f3d' }}>Sub Total</td>
            <td style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 700 }}>{formatRupiah(kalkulasi.subTotal, false)}</td>
          </tr>
          <tr style={{ background: '#f8fafc' }}>
            <td colSpan={5} style={{ padding: '5px 10px', color: '#64748b', fontSize: 12 }}>PPN 11%</td>
            <td style={{ padding: '5px 10px', textAlign: 'right', color: '#64748b', fontSize: 12 }}>{formatRupiah(kalkulasi.ppn, false)}</td>
          </tr>
          <tr style={{ background: '#0f1f3d', color: 'white' }}>
            <td colSpan={5} style={{ padding: '9px 10px', fontWeight: 700, fontSize: 14 }}>Grand Total</td>
            <td style={{ padding: '9px 10px', textAlign: 'right', fontWeight: 800, fontSize: 14 }}>{formatRupiah(kalkulasi.grandTotal, false)}</td>
          </tr>
        </tbody>
      </table>

      <div style={{ background: '#f8fafc', borderRadius: 8, padding: '9px 12px', fontSize: 12, color: '#374151', margin: '12px 0', fontStyle: 'italic' }}>
        Terbilang : {terbilang(kalkulasi.grandTotal)}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: 8 }}>
        <div style={{ fontSize: 11.5, color: '#64748b' }}>
          <div style={{ fontWeight: 600, color: '#374151', marginBottom: 2 }}>PT. SARANA GEMILANG</div>
          <div>Jl. Raya Pelabuhan No.1 Belawan I, Medan</div>
          <div style={{ marginTop: 4 }}>a/c 1200080070001 Bank Mandiri Cabang Jakarta</div>
        </div>
        <div style={{ textAlign: 'center', fontSize: 12, color: '#374151' }}>
          <div>Belawan, {formatTanggalIndo(tanggalInvoice)}</div>
          <div style={{ marginTop: 40, borderTop: '1px solid #374151', paddingTop: 4 }}>Administrasi</div>
        </div>
      </div>
    </div>
  )
}

// ─── Container Card ───────────────────────────────────────────────────────────
function ContainerCard({ c, idx, total, onChange, onRemove, tarifData }) {
  const set = (key, val) => onChange(c.id, key, val)
  const tarifStandar = c.ukuran === "20'"
    ? (tarifData?.paketLoloTrucking20 ?? 0)
    : (tarifData?.paketLoloTrucking40 ?? 0)

  return (
    <div style={{ border: '1.5px solid #e2e8f0', borderRadius: 12, overflow: 'hidden', background: 'white' }}>
      {/* Card header */}
      <div style={{
        background: 'linear-gradient(90deg, #064e3b, #065f46)',
        padding: '10px 16px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Warehouse size={15} color="#6ee7b7" />
          <span style={{ fontSize: 13, fontWeight: 700, color: 'white' }}>Container {idx + 1}</span>
          {c.ukuran && (
            <span style={{ background: 'rgba(110,231,183,0.2)', color: '#6ee7b7', fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 20 }}>
              {c.ukuran}
            </span>
          )}
          {/* Tampilkan tarif efektif langsung di header */}
          <span style={{ background: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.7)', fontSize: 11, padding: '2px 8px', borderRadius: 20 }}>
            {formatRupiah(c.overrideLolo !== '' ? (parseFloat(c.overrideLolo) || 0) : tarifStandar)}
          </span>
        </div>
        {total > 1 && (
          <button onClick={() => onRemove(c.id)} style={{
            background: 'rgba(239,68,68,0.15)', border: 'none', borderRadius: 6,
            padding: '4px 8px', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 4,
            color: '#fca5a5', fontSize: 11, fontWeight: 600,
          }}>
            <Trash2 size={12} /> Hapus
          </button>
        )}
      </div>

      {/* Card body */}
      <div style={{ padding: '16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Nomor Container" required>
          <Input value={c.nomorContainer} onChange={e => set('nomorContainer', e.target.value)} placeholder="CSNU0000000/SEAL000" />
        </Field>
        <Field label="Ukuran" required>
          <Select
            value={c.ukuran}
            onChange={e => set('ukuran', e.target.value)}
            options={UKURAN_CONTAINER.map(u => ({ value: u, label: u }))}
          />
        </Field>
        <Field label="Nama Kapal">
          <Input value={c.kapal} onChange={e => set('kapal', e.target.value)} placeholder="MV. INTEGRA" />
        </Field>
        <Field label="Voyage">
          <Input value={c.voyage} onChange={e => set('voyage', e.target.value)} placeholder="V.163E" />
        </Field>
        <Field label="Override Tarif Lolo" hint="Kosongkan = pakai standar">
          <Input
            type="number" value={c.overrideLolo}
            onChange={e => set('overrideLolo', e.target.value)}
            placeholder={`Standar: ${formatRupiah(tarifStandar)}`}
          />
        </Field>
      </div>
    </div>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────
export default function InputGudangUmum() {
  const { tarif, klienList, invoiceList, tambahInvoice, showToast } = useApp()
  const [form, setForm] = useState(initialForm)
  const [showPreview, setShowPreview] = useState(false)
  const [showConfirmSimpan, setShowConfirmSimpan] = useState(false)
  const [showConfirmReset, setShowConfirmReset] = useState(false)

  const setField = (key, val) => setForm(prev => ({ ...prev, [key]: val }))

  const handleKlienChange = (klienId) => {
    const klien = klienList.find(k => k.id === klienId)
    if (klien) {
      setForm(prev => ({ ...prev, klienId, consignee: klien.nama, alamat: klien.alamat, npwp: klien.npwp }))
    } else {
      setField('klienId', klienId)
    }
  }

  const handleContainerChange = (id, key, val) => {
    setForm(prev => ({
      ...prev,
      containers: prev.containers.map(c => c.id === id ? { ...c, [key]: val } : c),
    }))
  }

  const tarifData = tarif.gudangUmum || {}

  const kalkulasi = useMemo(() => {
    const perContainer = form.containers.map(c => hitungPerContainer(c, tarifData))
    const subTotal = perContainer.reduce((s, pc) => s + pc.subTotal, 0)
    const ppn = Math.round(subTotal * 0.11)
    const grandTotal = subTotal + ppn
    return { perContainer, subTotal, ppn, grandTotal }
  }, [form, tarifData])

  const previewData = useMemo(() => ({
    form, kalkulasi,
    nomorKW: '(dari server)',
    tanggalInvoice: new Date(),
  }), [form, kalkulasi])

  const isFormValid = form.consignee &&
    form.containers.every(c => c.nomorContainer)

  const handleSimpan = () => setShowConfirmSimpan(true)

  const eksekusiSimpan = async () => {
    try {
      const created = await tambahInvoice({
        jenisLayanan: 'Gudang Umum',
        consignee: form.consignee,
        klienId: form.klienId || null,
        subTotal: kalkulasi.subTotal,
        ppn: kalkulasi.ppn,
        grandTotal: kalkulasi.grandTotal,
        tpsAsal: 0,
        totalAkhir: kalkulasi.grandTotal,
        catatan: form.catatan || '',
        detailSnapshot: { form, kalkulasi },
        baris: kalkulasi.perContainer.flatMap(pc => pc.baris),
      })
      setShowPreview(false)
      setForm(initialForm)
      showToast(`Invoice Gudang Umum ${created.nomorKW} berhasil disimpan!`, 'sukses')
    } catch {
      // Error sudah ditampilkan oleh AppContext
    }
  }

  return (
    <div style={{ flex: 1 }}>
      <PageHeader
        title="Gudang Umum"
        subtitle="Input transaksi Gudang Umum (non-TPP) — Paket Lolo & Trucking"
      />



      <div style={{ padding: '24px 32px', display: 'grid', gridTemplateColumns: '1fr 300px', gap: 24, alignItems: 'start' }}>

        {/* ── Kiri ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* Banner info */}
          <div style={{
            background: 'linear-gradient(135deg, #ecfdf5, #d1fae5)',
            border: '1px solid #a7f3d0', borderRadius: 12, padding: '14px 18px',
            fontSize: 13, color: '#065f46',
            display: 'flex', alignItems: 'flex-start', gap: 10,
          }}>
            <Warehouse size={18} color="#10b981" style={{ flexShrink: 0, marginTop: 1 }} />
            <div>
              <strong>Gudang Umum (non-TPP)</strong> — Layanan ini hanya mencakup <strong>Paket Lolo & Trucking</strong> tanpa komponen Jasa TPP, Storage, atau Behandle. Sesuai format KW-014 (kertas pink).
            </div>
          </div>

          {/* Data Consignee */}
          <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e8edf2', padding: '20px 24px' }}>
            <SectionTitle>Data Consignee</SectionTitle>
            <div style={{ display: 'grid', gap: 14, marginTop: 12 }}>
              <Field label="Pilih dari Master Klien">
                <Select
                  value={form.klienId}
                  onChange={e => handleKlienChange(e.target.value)}
                  options={[
                    { value: '', label: '— Pilih klien atau isi manual —' },
                    ...klienList.map(k => ({ value: k.id, label: k.nama })),
                  ]}
                />
              </Field>
              <Field label="Nama Consignee" required>
                <Input value={form.consignee} onChange={e => setField('consignee', e.target.value)} placeholder="PT. NAMA PERUSAHAAN" />
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <Field label="Alamat">
                  <Input value={form.alamat} onChange={e => setField('alamat', e.target.value)} placeholder="Alamat lengkap" />
                </Field>
                <Field label="NPWP">
                  <Input value={form.npwp} onChange={e => setField('npwp', e.target.value)} placeholder="0000 0000 0000 0000" />
                </Field>
              </div>
              <Field label="Catatan (opsional)">
                <Input value={form.catatan} onChange={e => setField('catatan', e.target.value)} placeholder="Catatan tambahan..." />
              </Field>
            </div>
          </div>

          {/* Daftar Container */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#64748b' }}>
                Data Container ({form.containers.length})
              </div>
              <button
                onClick={() => setForm(prev => ({ ...prev, containers: [...prev.containers, newContainer()] }))}
                style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  padding: '7px 14px', borderRadius: 8, fontSize: 13, fontWeight: 600,
                  border: '1.5px dashed #10b981', background: '#f0fdf4',
                  color: '#065f46', cursor: 'pointer', fontFamily: 'inherit',
                }}
              >
                <Plus size={14} /> Tambah Container
              </button>
            </div>
            {form.containers.map((c, idx) => (
              <ContainerCard
                key={c.id} c={c} idx={idx}
                total={form.containers.length}
                onChange={handleContainerChange}
                onRemove={id => setForm(prev => ({ ...prev, containers: prev.containers.filter(c => c.id !== id) }))}
                tarifData={tarifData}
              />
            ))}
          </div>
        </div>

        {/* ── Kanan: Kalkulasi ── */}
        <div style={{ position: 'sticky', top: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* Ringkasan */}
          <div style={{
            background: 'linear-gradient(135deg, #064e3b, #065f46)',
            borderRadius: 12, padding: '14px 18px',
          }}>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
              Ringkasan Container
            </div>
            {form.containers.map((c, idx) => {
              const pc = kalkulasi.perContainer[idx]
              return (
                <div key={c.id} style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '6px 0',
                  borderBottom: idx < form.containers.length - 1 ? '1px solid rgba(255,255,255,0.08)' : 'none',
                }}>
                  <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.8)', fontWeight: 600 }}>
                    #{idx + 1} {c.ukuran || '—'}
                    {c.nomorContainer && <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', marginLeft: 6 }}>{c.nomorContainer.slice(0, 10)}</span>}
                  </span>
                  <span style={{ fontSize: 12.5, color: 'white', fontWeight: 700 }}>
                    {pc ? formatRupiah(pc.subTotal) : 'Rp 0'}
                  </span>
                </div>
              )
            })}
          </div>

          {/* Total */}
          <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e8edf2', overflow: 'hidden' }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Calculator size={15} color="#10b981" />
              <span style={{ fontSize: 13, fontWeight: 700, color: '#0f1f3d' }}>Total Kalkulasi</span>
            </div>
            <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 7 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12.5, color: '#64748b' }}>Sub Total ({form.containers.length} container)</span>
                <span style={{ fontSize: 12.5, fontWeight: 600 }}>{formatRupiah(kalkulasi.subTotal)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12.5, color: '#64748b' }}>PPN 11%</span>
                <span style={{ fontSize: 12.5, color: '#64748b' }}>{formatRupiah(kalkulasi.ppn)}</span>
              </div>
              <div style={{
                display: 'flex', justifyContent: 'space-between',
                background: '#0f1f3d', borderRadius: 8, padding: '10px 12px', margin: '4px -4px 0',
              }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: 'white' }}>Grand Total</span>
                <span style={{ fontSize: 14, fontWeight: 800, color: '#6ee7b7' }}>{formatRupiah(kalkulasi.grandTotal)}</span>
              </div>
            </div>
          </div>

          {/* Tombol */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <button onClick={() => setShowPreview(true)} disabled={!isFormValid} style={{
              padding: '11px 16px', borderRadius: 10, fontSize: 13.5, fontWeight: 600,
              cursor: isFormValid ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              border: '1.5px solid #10b981', background: '#f0fdf4', color: '#065f46',
              opacity: isFormValid ? 1 : 0.5,
            }}>
              <Eye size={16} /> Preview Invoice
            </button>
            <button onClick={handleSimpan} disabled={!isFormValid} style={{
              padding: '11px 16px', borderRadius: 10, fontSize: 13.5, fontWeight: 600,
              cursor: isFormValid ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              border: 'none',
              background: isFormValid ? 'linear-gradient(135deg, #10b981, #065f46)' : '#e2e8f0',
              color: isFormValid ? 'white' : '#94a3b8',
              opacity: isFormValid ? 1 : 0.7,
            }}>
              <Save size={16} /> Simpan Invoice
            </button>
            <button onClick={() => setShowConfirmReset(true)} style={{
              padding: '9px 16px', borderRadius: 10, fontSize: 13, fontWeight: 500,
              cursor: 'pointer', fontFamily: 'inherit',
              border: '1px solid #e2e8f0', background: 'white', color: '#64748b',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              <RotateCcw size={14} /> Reset Form
            </button>
          </div>
        </div>
      </div>

      <ConfirmDialog
        isOpen={showConfirmSimpan}
        onClose={() => setShowConfirmSimpan(false)}
        onConfirm={eksekusiSimpan}
        tipe="simpan"
        judul="Simpan Invoice Gudang Umum?"
        pesan="Pastikan semua data sudah benar sebelum disimpan."
        detail={[
          { label: 'Consignee', value: form.consignee || '-' },
          { label: 'Jumlah Container', value: `${form.containers.length} unit` },
          { label: 'Grand Total', value: formatRupiah(kalkulasi.grandTotal) },
        ]}
      />
      <ConfirmDialog
        isOpen={showConfirmReset}
        onClose={() => setShowConfirmReset(false)}
        onConfirm={() => { setForm(initialForm); showToast('Form berhasil direset.', 'info') }}
        tipe="reset"
        judul="Reset semua isian form?"
        pesan="Semua data yang sudah Anda isi akan dihapus dan form kembali kosong."
      />
      <Modal isOpen={showPreview} onClose={() => setShowPreview(false)} title="Preview Invoice Gudang Umum" width={680}>
        <PreviewInvoice data={previewData} />
        <div style={{ display: 'flex', gap: 10, marginTop: 20, justifyContent: 'flex-end' }}>
          <button onClick={() => setShowPreview(false)} style={{
            padding: '9px 20px', borderRadius: 8, border: '1px solid #e2e8f0',
            background: 'white', color: '#64748b', fontSize: 13.5, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>Tutup</button>
          <button onClick={eksekusiSimpan} style={{
            padding: '9px 20px', borderRadius: 8, border: 'none',
            background: 'linear-gradient(135deg, #10b981, #065f46)',
            color: 'white', fontSize: 13.5, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Save size={15} /> Simpan Invoice
          </button>
        </div>
      </Modal>
    </div>
  )
}
