import React, { useState, useMemo, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useApp } from '../context/AppContext'
import { useAuth } from '../context/AuthContext'
import { formatRupiah } from '../utils/formatRupiah'
import { buildInvoicePayload } from '../utils/buildInvoicePayload'
import PageHeader from '../components/PageHeader'
import ConfirmDialog from '../components/ConfirmDialog'
import { TARIF_DEFAULT } from '../data/tarifDefault'
import { Button } from '../components/ui/Button'
import { Card, CardHeader, CardTitle, CardContent } from '../components/ui/Card'
import {
  Search, Save, RotateCcw, Calculator,
  Container, CheckCircle2, Warehouse,
  FileText, Calendar, ChevronDown, ChevronUp, Trash2,
} from 'lucide-react'
import { hitungHariStorage as hitungHari } from '../utils/hitungStorage'

//  Hitung hari (inklusif: tgl masuk dihitung 1 hari) 
// Dikonfirmasi dari invoice KW-055 dan KW-042:
//   Total hari = (tglKeluar - tglMasuk) + 1
//   Free time  = 5 hari pertama → storage dicharge mulai hari ke-6

const FREE_TIME_DEFAULT = 5

function hitungHariCharge(totalHari, freeTime = FREE_TIME_DEFAULT) {
  return Math.max(0, totalHari - freeTime)
}

function fmtTgl(t) {
  if (!t) return '-'
  try {
    const d = new Date(t)
    const b = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des']
    return `${String(d.getDate()).padStart(2,'0')}-${b[d.getMonth()]}-${d.getFullYear()}`
  } catch { return t }
}

//  Hitung per container 
function hitungContainer(c, tarifGudang) {
  const freeTime   = tarifGudang.freeTimeDays ?? FREE_TIME_DEFAULT
  const hari       = hitungHari(c.tglMasuk, c.tglKeluar)
  const hariCharge = hitungHariCharge(hari, freeTime)
  const baris = []

  // Lolo rate per ukuran
  const loloStd = c.ukuran === "20'"
    ? tarifGudang.paketLoloTrucking20 ?? 0
    : c.ukuran === "40'"
      ? tarifGudang.paketLoloTrucking40 ?? 0
      : tarifGudang.paketLoloTruckingFR ?? 0

  // Storage rate per ukuran (sama dari invoice, tapi simpan per-ukuran agar fleksibel)
  const storStd = c.ukuran === "20'"
    ? tarifGudang.storage20PerHari ?? 0
    : c.ukuran === "40'"
      ? tarifGudang.storage40PerHari ?? 0
      : tarifGudang.storageFRPerHari ?? 0

  const lolo    = (c.overrideLolo    != null && c.overrideLolo    !== '') ? parseFloat(c.overrideLolo)    || 0 : loloStd
  const storage = (c.overrideStorage != null && c.overrideStorage !== '') ? parseFloat(c.overrideStorage) || 0 : storStd

  const is20 = c.ukuran === "20'"
  const qty  = { qty20: is20 ? 1 : '', qty40: !is20 ? 1 : '' }

  if (lolo > 0)
    baris.push({ label: 'Paket Lolo dan Trucking', tarif: lolo, jumlah: lolo, ...qty })
  if (storage > 0 && hariCharge > 0)
    baris.push({ label: 'Pengelolaan Penyimpanan', tarif: storage, jumlah: storage * hariCharge, hari: hariCharge, ...qty })

  return {
    baris,
    subTotal: baris.reduce((s, b) => s + b.jumlah, 0),
    hari, hariCharge, ukuran: c.ukuran, nomorContainer: c.nomorContainer,
    tglMasuk: c.tglMasuk, tglKeluar: c.tglKeluar,
    loloStd, storStd,
  }
}

//  Lookup B/L 
function LookupPanel({ gudangList, onSelect, selected, isDocInvoiced, isAdmin, onHapus }) {
  const [q, setQ] = useState('')
  const allFcl = gudangList.filter(d => !d.jenisTransaksi || d.jenisTransaksi.toLowerCase() === 'fcl')
  const filtered  = allFcl
    .filter(d => !isDocInvoiced(d.id))
    .filter(d =>
      d.blNomor?.toLowerCase().includes(q.toLowerCase()) ||
      d.consignee?.toLowerCase().includes(q.toLowerCase())
    )

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ position: 'relative' }}>
        <Search size={14} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#94a3b8', pointerEvents: 'none' }} />
        <input value={q} onChange={e => setQ(e.target.value)}
          placeholder="Cari nomor B/L atau consignee..."
          style={{ width: '100%', height: 40, borderRadius: 8, border: '1.5px solid #e2e8f0', paddingLeft: 36, paddingRight: 12, fontSize: 13, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }}
          onFocus={e => e.target.style.borderColor = '#10b981'}
          onBlur={e => e.target.style.borderColor = '#e2e8f0'}
        />
      </div>
      {allFcl.length === 0 ? (
        <div style={{ padding: '28px 20px', textAlign: 'center', background: '#f8fafc', borderRadius: 10, border: '1.5px dashed #e2e8f0' }}>
          <Warehouse size={26} color="#cbd5e1" style={{ margin: '0 auto 8px' }} />
          <div style={{ fontSize: 13.5, fontWeight: 600, color: '#64748b' }}>Tidak ada data Gudang FCL</div>
          <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 4 }}>Input dokumen dan pilih <strong>FCL</strong> di menu Input Gudang</div>
        </div>
      ) : filtered.length === 0 ? (
        <div style={{ textAlign: 'center', color: '#94a3b8', fontSize: 13, padding: 16 }}>Tidak ditemukan.</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 280, overflowY: 'auto' }}>
          {filtered.map(d => {
            const sel = selected?.id === d.id
            const ctrCount = d.containers?.length || 0
            return (
              <div key={d.id} style={{ position: 'relative' }}>
                <button onClick={() => onSelect(d)} style={{
                  width: '100%', padding: isAdmin ? '12px 48px 12px 14px' : '12px 14px',
                  borderRadius: 10, textAlign: 'left', cursor: 'pointer',
                  fontFamily: 'inherit', transition: 'all 0.15s',
                  border: `1.5px solid ${sel ? '#10b981' : '#e2e8f0'}`,
                  background: sel ? 'rgba(16,185,129,0.06)' : 'white',
                  boxShadow: sel ? '0 0 0 3px rgba(16,185,129,0.12)' : 'none',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div>
                      <div style={{ fontSize: 13.5, fontWeight: 700, color: '#0f172a' }}>{d.blNomor}</div>
                      <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>{d.consignee}</div>
                      {ctrCount > 0 && (
                        <div style={{ fontSize: 11.5, color: '#94a3b8', marginTop: 2 }}>
                          {ctrCount} container · {[...new Set(d.containers.map(c => c.ukuran).filter(Boolean))].join(', ')}
                        </div>
                      )}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
                      <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 20, background: '#ecfdf5', color: '#065f46' }}>{d.status}</span>
                      {sel && <CheckCircle2 size={16} color="#10b981" />}
                    </div>
                  </div>
                </button>
                {/* Delete button — khusus admin */}
                {isAdmin && (
                  <button
                    onClick={e => { e.stopPropagation(); onHapus(d) }}
                    title="Hapus dokumen ini (Admin)"
                    style={{
                      position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
                      width: 28, height: 28, borderRadius: 7, border: '1px solid #fecaca',
                      background: '#fff5f5', cursor: 'pointer', display: 'flex',
                      alignItems: 'center', justifyContent: 'center', transition: 'all 0.15s',
                    }}
                    onMouseEnter={e => { e.currentTarget.style.background = '#fee2e2'; e.currentTarget.style.borderColor = '#f87171' }}
                    onMouseLeave={e => { e.currentTarget.style.background = '#fff5f5'; e.currentTarget.style.borderColor = '#fecaca' }}
                  >
                    <Trash2 size={13} color="#ef4444" />
                  </button>
                )}
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}

//  Container Summary (read-only, collapsible) 
function ContainerEditor({ containers, tarifGudang, onUpdateTglKeluar }) {
  const [open, setOpen] = useState(true)
  if (!containers?.length) return null
  const storRate = tarifGudang?.storage20PerHari || 0

  return (
    <div style={{ borderRadius: 10, border: '1px solid #e2e8f0', overflow: 'hidden' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: '100%', padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
        background: '#f0fdf4', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
        borderBottom: open ? '1px solid #e2e8f0' : 'none',
      }}>
        <Container size={14} color="#059669" />
        <span style={{ flex: 1, textAlign: 'left', fontSize: 13, fontWeight: 700, color: '#059669' }}>
          {containers.length} Container — Konfirmasi Tanggal Keluar
        </span>
        <span style={{ fontSize: 11, color: '#64748b', fontWeight: 400 }}>Edit jika berbeda</span>
        {open ? <ChevronUp size={13} color="#94a3b8" /> : <ChevronDown size={13} color="#94a3b8" />}
      </button>
      {open && containers.map((c, i) => {
        const hari = hitungHari(c.tglMasuk, c.tglKeluar)
        return (
          <div key={i} style={{
            padding: '12px 14px',
            borderTop: '1px solid #f1f5f9',
            background: hari > 0 ? 'white' : '#fffbeb',
          }}>
            {/* Header container */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: 'white', background: '#059669', padding: '2px 8px', borderRadius: 6, fontFamily: 'monospace' }}>
                {c.nomorContainer || `Container ${i+1}`}
              </span>
              <span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 6,
                background: c.ukuran === "20'" ? '#eff6ff' : '#faf5ff',
                color: c.ukuran === "20'" ? '#1d4ed8' : '#6d28d9',
              }}>{c.ukuran}</span>
              {c.kapal && <span style={{ fontSize: 11.5, color: '#64748b' }}>{c.kapal}{c.voyage && ` / ${c.voyage}`}</span>}
            </div>
            {/* Tanggal masuk & keluar */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#94a3b8', marginBottom: 4 }}>Tanggal Masuk</div>
                <div style={{ height: 36, borderRadius: 8, border: '1.5px solid #e2e8f0', padding: '0 12px', fontSize: 13, display: 'flex', alignItems: 'center', background: '#f8fafc', color: '#64748b' }}>
                  {c.tglMasuk ? fmtTgl(c.tglMasuk) : '—'}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: hari > 0 ? '#059669' : '#f97316', marginBottom: 4 }}>
                  Tanggal Keluar {hari > 0 ? `✓ (${hari} hari)` : '⚠  Belum diisi'}
                </div>
                <input
                  type="date"
                  value={c.tglKeluar || ''}
                  onChange={e => onUpdateTglKeluar(i, e.target.value)}
                  min={c.tglMasuk || ''}
                  style={{
                    width: '100%', height: 36, borderRadius: 8,
                    border: `1.5px solid ${hari > 0 ? '#10b981' : '#fed7aa'}`,
                    padding: '0 12px', fontSize: 13, fontFamily: 'inherit',
                    outline: 'none', background: hari > 0 ? '#f0fdf4' : '#fffbeb',
                    boxSizing: 'border-box',
                  }}
                />
              </div>
            </div>
            {/* Storage preview */}
            {hari > 0 && storRate > 0 && (
              <div style={{ marginTop: 8, fontSize: 12, color: '#059669', display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
                <Calendar size={11} />
                {(() => {
                  const hariCharge = Math.max(0, hari - (tarifGudang.freeTimeDays ?? FREE_TIME_DEFAULT))
                  const freeTime = tarifGudang.freeTimeDays ?? FREE_TIME_DEFAULT
                  return hariCharge > 0
                    ? <span>Storage: <strong>{hari} hari total</strong> — free {freeTime} hari → charge <strong>{hariCharge} hari × {formatRupiah(storRate)} = {formatRupiah(hariCharge * storRate)}</strong></span>
                    : <span style={{ color: '#94a3b8' }}>Storage: {hari} hari — <strong>dalam free time ({freeTime} hari), tidak dicharge</strong></span>
                })()}
                <span style={{ color: '#94a3b8' }}>({fmtTgl(c.tglMasuk)} → {fmtTgl(c.tglKeluar)})</span>
              </div>
            )}
          </div>
        )
      })}
    </div>
  )
}

//  Toggle biaya 
function BiayaToggle({ label, sub, checked, onChange, jumlah }) {
  return (
    <div onClick={() => onChange(!checked)} style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '11px 14px', borderRadius: 10, cursor: 'pointer', userSelect: 'none',
      border: `1.5px solid ${checked ? '#10b981' : '#e2e8f0'}`,
      background: checked ? 'rgba(16,185,129,0.06)' : '#fafafa', transition: 'all 0.15s',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 20, height: 20, borderRadius: 5, flexShrink: 0, transition: 'all 0.15s', border: `2px solid ${checked ? '#10b981' : '#cbd5e1'}`, background: checked ? '#10b981' : 'white', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {checked && <span style={{ fontSize: 10, fontWeight: 900, color: 'white' }}>✓</span>}
        </div>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: checked ? '#0f172a' : '#94a3b8' }}>{label}</div>
          {sub && <div style={{ fontSize: 11.5, color: '#94a3b8' }}>{sub}</div>}
        </div>
      </div>
      <span style={{ fontSize: 13, fontWeight: 700, color: checked ? '#059669' : '#cbd5e1' }}>{formatRupiah(jumlah)}</span>
    </div>
  )
}

//  Main 
const initForm = {
  includeJasaGudang:   false,
  includeAdministrasi: false,
  includeFumigasi:     false,
  // Input bebas
  biayaLainLain: [],
  // Diskon
  diskon: '',
  catatan: '',
  // Gudang Umum: NPWP, Alamat, Free Time override (editable)
  npwpOverride: '',
  alamatOverride: '',
  freeTimeOverride: '',
}

export default function GudangFCL() {
  const { tarif, gudangList, invoiceList, tambahInvoice, hapusGudang, showToast, isDocInvoiced, klienList } = useApp()
  const { isAdmin } = useAuth()
  const location = useLocation()

  const [form, setForm]   = useState(initForm)
  const [doc, setDoc]     = useState(null)
  const [tujuan, setTujuan] = useState('full_ekspor')
  const [showConfirm, setShowConfirm]         = useState(false)
  const [showConfirmReset, setShowConfirmReset] = useState(false)
  const [hapusTarget, setHapusTarget]         = useState(null) // dokumen yang akan dihapus
  const [saving, setSaving] = useState(false)

  // editableContainers — salinan container dari doc yang bisa di-edit tglKeluar per container
  // Gudang Umum FCL bisa punya container keluar di hari berbeda → storage dihitung masing-masing
  const [editableContainers, setEditableContainers] = useState([])

  // FIX: handleHapus harus async agar toast hanya muncul setelah backend sukses
  const handleHapus = async (d) => {
    if (doc?.id === d.id) { setDoc(null); setEditableContainers([]) }
    try {
      await hapusGudang(d.id)
      showToast(`Dokumen ${d.blNomor} berhasil dihapus.`, 'sukses')
    } catch {
      // Error sudah ditampilkan oleh hapusGudang via showToast di AppContext
    } finally {
      setHapusTarget(null)
    }
  }

  const handleUpdateTglKeluar = (idx, tglKeluar) => {
    setEditableContainers(prev => prev.map((c, i) => i === idx ? { ...c, tglKeluar } : c))
  }

  const set = (k, v) => setForm(p => ({ ...p, [k]: v }))

  // Resolusi tarif efektif: merge tarifKhusus klien jika ada
  const tarifGudang = useMemo(() => {
    const namaKlien = doc?.consignee || ''
    const klien = namaKlien
      ? klienList?.find(k => k.nama?.toLowerCase() === namaKlien.toLowerCase())
      : null
    const khusus = klien?.tarifKhusus?.gudangUmum || {}
    // Jika klien punya freeTimeDays khusus, override ke tarifGudang agar hitungContainer pakai nilai ini
    const freeTimeOverride = (form.freeTimeOverride !== '' && form.freeTimeOverride != null)
      ? { freeTimeDays: parseInt(form.freeTimeOverride) || 0 }
      : (klien?.freeTimeDays != null) ? { freeTimeDays: klien.freeTimeDays } : {}
    return { ...(TARIF_DEFAULT.gudangUmum), ...(tarif.gudangUmum || {}), ...khusus, ...freeTimeOverride }
  }, [doc, klienList, tarif, form.freeTimeOverride])

  const addBiayaLain    = () => setForm(p => ({ ...p, biayaLainLain: [...p.biayaLainLain, { nama:'', nominal:'' }] }))
  const removeBiayaLain = (i) => setForm(p => ({ ...p, biayaLainLain: p.biayaLainLain.filter((_,idx) => idx !== i) }))
  const updateBiayaLain = (i, field, val) => setForm(p => ({
    ...p, biayaLainLain: p.biayaLainLain.map((b,idx) => idx===i ? { ...b, [field]:val } : b)
  }))

  const handleSelectDoc = (d) => {
    setDoc(d)
    setEditableContainers(d.containers ? d.containers.map(c => ({ ...c })) : [])
    // Auto-fill NPWP & Alamat dari Master Klien jika consignee match
    const namaKlien = d?.consignee || ''
    const klienMatch = namaKlien
      ? klienList?.find(k => k.nama?.toLowerCase() === namaKlien.toLowerCase())
      : null
    if (klienMatch) {
      setForm(p => ({
        ...p,
        npwpOverride: klienMatch.npwp || '',
        alamatOverride: klienMatch.alamat || '',
        freeTimeOverride: klienMatch.freeTimeDays != null ? String(klienMatch.freeTimeDays) : '',
      }))
    } else {
      setForm(p => ({ ...p, npwpOverride: '', alamatOverride: '', freeTimeOverride: '' }))
    }
  }

  // Auto-fill dari redirect DataGudangUmum
  useEffect(() => {
    const prefill = location.state?.prefill
    if (!prefill?.doc) return
    setDoc(prefill.doc)
    setEditableContainers(prefill.doc.containers ? prefill.doc.containers.map(c => ({ ...c })) : [])
    if (prefill.tujuan) setTujuan(prefill.tujuan)
    window.history.replaceState({}, document.title)
  }, [])

  const containers = editableContainers

  // Kalkulasi
  const kalkulasi = useMemo(() => {
    const perContainer = containers.map(c => hitungContainer(c, tarifGudang))
    const jasaGudang   = form.includeJasaGudang   ? (tarifGudang.jasaGudang    || 0) : 0
    const administrasi = form.includeAdministrasi  ? (tarifGudang.administrasi  || 0) : 0
    const fumigasi     = form.includeFumigasi       ? containers.length * (tarifGudang.fumigasi || 0) : 0
    const totalBiayaLainLain = form.biayaLainLain.reduce((s, b) => s + (parseFloat(String(b.nominal).replace(/\./g,'').replace(',','.')) || 0), 0)
    const subTotal  = perContainer.reduce((s, p) => s + p.subTotal, 0) + jasaGudang + administrasi + fumigasi + totalBiayaLainLain
    const diskon    = parseFloat(String(form.diskon).replace(/\./g,'').replace(',','.')) || 0
    const dpp       = Math.max(0, subTotal - diskon)
    const ppn       = Math.round(dpp * 0.11)
    const grandTotal = dpp + ppn
    return { perContainer, jasaGudang, administrasi, fumigasi, totalBiayaLainLain, subTotal, diskon, dpp, ppn, grandTotal }
  }, [containers, form, tarifGudang])

  const isValid = !!doc && containers.length > 0

  const eksekuSimpan = async () => {
    if (saving) return
    setSaving(true)
    const namaKlien = doc?.consignee || ''
    const klien = klienList?.find(k => k.nama?.toLowerCase() === namaKlien.toLowerCase())
    const tujuanLabel = tujuan === 'wh_importir' ? 'WH Importir' : 'Full Ekspor'

    // GudangFCL: doc dari gudangList, tipeDokumen = 'gudang'
    const docWithContainers = { ...doc, containers: editableContainers, pemilikBarang: namaKlien }

    const payload = buildInvoicePayload({
      doc: docWithContainers,
      tipeDokumen: 'gudang',
      jenisLayanan: 'Gudang Umum FCL',
      tujuan: tujuanLabel,
      kalkulasi,
      form: { ...form, tujuan },
      klien,
      jumlahContainer: containers.length,
      overrideNpwp: form.npwpOverride,
      overrideAlamat: form.alamatOverride,
    })

    try {
      const created = await tambahInvoice(payload)
      setDoc(null); setForm(initForm); setEditableContainers([])
      showToast(`Invoice Gudang FCL ${created.nomorKW} berhasil diterbitkan!`, 'sukses')
    } catch {
      // Error sudah ditampilkan oleh AppContext via showToast
    } finally {
      setSaving(false)
    }
  }

  return (
    <div style={{ flex: 1 }}>
      <PageHeader title="Transaksi FCL — Gudang Umum" subtitle="Pilih dokumen Gudang (B/L) → Atur komponen biaya → Terbitkan invoice" />

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

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

          {/* Step 1: Pilih B/L */}
          <Card>
            <CardHeader>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 26, height: 26, borderRadius: '50%', background: doc ? '#10b981' : '#059669', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, color: 'white', flexShrink: 0 }}>{doc ? '✓' : '1'}</div>
                <CardTitle>Pilih Dokumen Gudang (B/L)</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <LookupPanel gudangList={gudangList} onSelect={handleSelectDoc} selected={doc} isDocInvoiced={isDocInvoiced} isAdmin={isAdmin} onHapus={setHapusTarget} />
            </CardContent>
          </Card>

          {doc && (
            <>
              {/* Info + Container Summary */}
              <Card>
                <CardContent style={{ paddingTop: 20 }}>
                  {/* Info B/L */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, padding: '12px 14px', background: '#f0fdf4', borderRadius: 10, border: '1px solid #bbf7d0' }}>
                    <CheckCircle2 size={18} color="#10b981" style={{ flexShrink: 0 }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#166534' }}>{doc.blNomor}</div>
                      <div style={{ fontSize: 12, color: '#4ade80', marginTop: 1 }}>{doc.consignee}</div>
                    </div>
                    <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 20, background: '#dcfce7', color: '#166534' }}>
                      {containers.length} container
                    </span>
                  </div>

                  {/* Tujuan */}
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: '#64748b', marginBottom: 8 }}>Tujuan Kegiatan</div>
                    <div style={{ display: 'flex', gap: 8 }}>
                      {[
                        { val: 'wh_importir',  label: 'WH Importir',  sub: 'Barang impor dititipkan ke warehouse' },
                        { val: 'full_ekspor', label: 'Full Ekspor',  sub: 'Barang keluar untuk ekspor' },
                      ].map(o => (
                        <button key={o.val} onClick={() => setTujuan(o.val)} style={{
                          flex: 1, padding: '8px 10px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
                          fontSize: 12.5, fontWeight: 700, transition: 'all 0.15s',
                          border: `2px solid ${tujuan === o.val ? '#10b981' : '#e2e8f0'}`,
                          background: tujuan === o.val ? '#f0fdf4' : 'white',
                          color: tujuan === o.val ? '#047857' : '#64748b',
                        }}>{o.label}</button>
                      ))}
                    </div>
                  </div>

                  {/* Container summary */}
                  {containers.length > 0
                    ? <ContainerEditor containers={editableContainers} tarifGudang={tarifGudang} onUpdateTglKeluar={handleUpdateTglKeluar} />
                    : (
                      <div style={{ padding: '12px 14px', background: '#fff7ed', borderRadius: 10, border: '1px solid #fed7aa', fontSize: 12.5, color: '#92400e' }}>
                        ⚠  Dokumen ini tidak memiliki data container. Pastikan data container sudah diisi saat input Gudang Umum.
                      </div>
                    )
                  }

                  {/* BUG2-FIX: Section Data Klien dihapus per permintaan client.
                   * NPWP/Alamat tetap di-auto-fill internal dari Master Klien di handleSelectDoc
                   * dan dikirim via payload invoice, hanya tidak ditampilkan sebagai form editable. */}
                </CardContent>
              </Card>

              {/* Step 2: Biaya Tambahan */}
              <Card>
                <CardHeader>
                  <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                    <div style={{ width:26, height:26, borderRadius:'50%', background:'#059669', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:800, color:'white', flexShrink:0 }}>2</div>
                    <CardTitle>Komponen Biaya Tambahan</CardTitle>
                  </div>
                </CardHeader>
                <CardContent>
                  <div style={{ display:'flex', flexDirection:'column', gap:16 }}>

                    {/* Preset toggle */}
                    <div>
                      <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.07em', textTransform:'uppercase', color:'#94a3b8', marginBottom:8 }}>Biaya Opsional — Centang Jika Ada</div>
                      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                        <BiayaToggle label="Fumigasi" sub="Per container — opsional" checked={form.includeFumigasi} onChange={v => set('includeFumigasi', v)} jumlah={(tarifGudang.fumigasi || 0) * containers.length} />
                        <BiayaToggle label="Jasa Gudang" sub="Flat per invoice — jika ada" checked={form.includeJasaGudang} onChange={v => set('includeJasaGudang', v)} jumlah={tarifGudang.jasaGudang || 0} />
                        <BiayaToggle label="Administrasi" sub="Flat per invoice — jika ada" checked={form.includeAdministrasi} onChange={v => set('includeAdministrasi', v)} jumlah={tarifGudang.administrasi || 0} />
                      </div>
                    </div>

                    {/* Input bebas */}
                    <div>
                      <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.07em', textTransform:'uppercase', color:'#94a3b8', marginBottom:8 }}>Input Biaya Tambahan Lain-Lain</div>
                      <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                        {form.biayaLainLain.map((b, i) => (
                          <div key={i} style={{ display:'flex', alignItems:'center', gap:8 }}>
                            <input value={b.nama} onChange={e => updateBiayaLain(i,'nama',e.target.value)}
                              placeholder="Nama biaya..."
                              style={{ flex:1, height:34, borderRadius:8, border:'1.5px solid #e2e8f0', padding:'0 10px', fontSize:13, fontFamily:'inherit', outline:'none' }}
                              onFocus={e => e.target.style.borderColor = '#10b981'}
                              onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                            />
                            <div style={{ display:'flex', alignItems:'center', gap:4, flexShrink:0 }}>
                              <span style={{ fontSize:12, color:'#94a3b8' }}>Rp</span>
                              <input type="number" min="0" value={b.nominal} onChange={e => updateBiayaLain(i,'nominal',e.target.value)}
                                placeholder="0"
                                style={{ width:130, height:34, borderRadius:8, border:'1.5px solid #e2e8f0', padding:'0 10px', fontSize:13, fontFamily:'inherit', outline:'none', textAlign:'right' }}
                                onFocus={e => e.target.style.borderColor = '#10b981'}
                                onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                              />
                            </div>
                            <button onClick={() => removeBiayaLain(i)} style={{ width:32, height:32, borderRadius:8, border:'1.5px solid #fecaca', background:'#fff5f5', color:'#dc2626', cursor:'pointer', fontFamily:'inherit', fontSize:14, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>✕</button>
                          </div>
                        ))}
                        <button onClick={addBiayaLain} style={{ height:34, borderRadius:8, border:'1.5px dashed #a7f3d0', background:'#f0fdf4', color:'#059669', fontSize:12.5, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>
                          + Tambah Baris Biaya
                        </button>
                      </div>
                    </div>

                    {/* Diskon */}
                    <div>
                      <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.07em', textTransform:'uppercase', color:'#94a3b8', marginBottom:8 }}>Diskon (Opsional)</div>
                      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 12px', borderRadius:10, border:'1.5px solid #e2e8f0', background:'#fafafa' }}>
                        <span style={{ fontSize:13, color:'#475569', flex:1 }}>Potongan Diskon</span>
                        <span style={{ fontSize:12, color:'#94a3b8' }}>Rp</span>
                        <input type="number" min="0" step="1000"
                          value={form.diskon} onChange={e => set('diskon', e.target.value)}
                          placeholder="0"
                          style={{ width:150, height:32, borderRadius:7, border:'1.5px solid #e2e8f0', padding:'0 10px', fontSize:13, fontFamily:'inherit', outline:'none', textAlign:'right', background:'white' }}
                          onFocus={e => e.target.style.borderColor = '#ef4444'}
                          onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                        />
                      </div>
                    </div>

                    {/* Catatan */}
                    <div>
                      <div style={{ fontSize:12, fontWeight:600, color:'#64748b', marginBottom:6 }}>Catatan (opsional)</div>
                      <textarea value={form.catatan} onChange={e => set('catatan', e.target.value)}
                        style={{ width:'100%', borderRadius:8, border:'1.5px solid #e2e8f0', padding:'10px 12px', fontSize:13, fontFamily:'inherit', outline:'none', resize:'vertical', boxSizing:'border-box' }}
                        rows={2} placeholder="Catatan tambahan untuk invoice..."
                        onFocus={e => e.target.style.borderColor = '#10b981'}
                        onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>
            </>
          )}
        </div>

        {/*  KANAN: Kalkulasi  */}
        <div style={{ position: 'sticky', top: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {!doc ? (
            <div style={{ padding: '40px 24px', textAlign: 'center', background: 'white', borderRadius: 16, border: '1.5px dashed #e2e8f0' }}>
              <Warehouse size={32} color="#cbd5e1" style={{ margin: '0 auto 12px' }} />
              <div style={{ fontSize: 13.5, fontWeight: 600, color: '#64748b' }}>Pilih dokumen Gudang (B/L)</div>
              <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 4 }}>untuk memulai kalkulasi</div>
            </div>
          ) : (
            <>
              {/* Info */}
              <div style={{ background: 'linear-gradient(135deg, #065f46, #047857)', borderRadius: 14, padding: 16 }}>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)', marginBottom: 4 }}>B/L Terpilih</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'white' }}>{doc.blNomor}</div>
                <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.5)', marginTop: 2 }}>{doc.consignee}</div>
                <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                  <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 20, background: 'rgba(255,255,255,0.15)', color: 'rgba(255,255,255,0.7)' }}>
                    {containers.length} container
                  </span>
                  <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 20, background: 'rgba(255,255,255,0.15)', color: 'rgba(255,255,255,0.7)' }}>
                    {tujuan === 'ekspor' ? 'Ekspor' : tujuan === 'stripping' ? 'Stripping' : 'Stuffing'}
                  </span>
                </div>
              </div>

              {/* Breakdown */}
              <Card>
                <CardHeader>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Calculator size={14} color="#10b981" />
                    <CardTitle>Kalkulasi</CardTitle>
                  </div>
                </CardHeader>
                <CardContent style={{ paddingTop: 0 }}>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    {kalkulasi.perContainer.map((pc, i) => pc.subTotal > 0 && (
                      <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                        <span style={{ color: '#64748b' }}>Container {i+1} ({pc.ukuran}){pc.hari > 0 ? ` · ${pc.hari} hr` : ''}</span>
                        <span style={{ fontWeight: 600, color: '#374151' }}>{formatRupiah(pc.subTotal)}</span>
                      </div>
                    ))}
                    {form.includeJasaGudang && kalkulasi.jasaGudang > 0 && (
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:12.5 }}><span style={{color:'#64748b'}}>Jasa Gudang</span><span style={{fontWeight:600,color:'#374151'}}>{formatRupiah(kalkulasi.jasaGudang)}</span></div>
                    )}
                    {form.includeAdministrasi && kalkulasi.administrasi > 0 && (
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:12.5 }}><span style={{color:'#64748b'}}>Administrasi</span><span style={{fontWeight:600,color:'#374151'}}>{formatRupiah(kalkulasi.administrasi)}</span></div>
                    )}
                    {form.includeFumigasi && kalkulasi.fumigasi > 0 && (
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:12.5 }}><span style={{color:'#64748b'}}>Fumigasi ({containers.length} unit)</span><span style={{fontWeight:600,color:'#374151'}}>{formatRupiah(kalkulasi.fumigasi)}</span></div>
                    )}
                    {form.biayaLainLain.filter(b => b.nama && parseFloat(b.nominal) > 0).map((b, i) => (
                      <div key={i} style={{ display:'flex',justifyContent:'space-between',fontSize:12.5 }}><span style={{color:'#64748b'}}>{b.nama}</span><span style={{fontWeight:600,color:'#374151'}}>{formatRupiah(parseFloat(b.nominal)||0)}</span></div>
                    ))}
                    <div style={{ borderTop:'1px solid #f1f5f9', paddingTop:6, marginTop:2, display:'flex', flexDirection:'column', gap:4 }}>
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:12.5 }}><span style={{color:'#64748b'}}>Sub Total</span><span style={{fontWeight:700,color:'#0f172a'}}>{formatRupiah(kalkulasi.subTotal)}</span></div>
                      {kalkulasi.diskon > 0 && (<div style={{ display:'flex',justifyContent:'space-between',fontSize:12.5 }}><span style={{color:'#ef4444'}}>Diskon</span><span style={{fontWeight:600,color:'#ef4444'}}>- {formatRupiah(kalkulasi.diskon)}</span></div>)}
                      {kalkulasi.diskon > 0 && (<div style={{ display:'flex',justifyContent:'space-between',fontSize:12.5 }}><span style={{color:'#64748b'}}>DPP</span><span style={{fontWeight:600,color:'#374151'}}>{formatRupiah(kalkulasi.dpp)}</span></div>)}
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:12.5 }}><span style={{color:'#64748b'}}>PPN 11%</span><span style={{color:'#64748b'}}>{formatRupiah(kalkulasi.ppn)}</span></div>
                    </div>
                    <div style={{ background: '#065f46', borderRadius: 10, padding: '10px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
                      <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>
                </CardContent>
              </Card>

              <Button onClick={() => setShowConfirm(true)} disabled={!isValid}
                style={{ height: 44, justifyContent: 'center', gap: 8, fontSize: 13.5, width: '100%', background: 'linear-gradient(135deg,#059669,#047857)', borderColor: 'transparent', color: 'white' }}>
                <Save size={16} /> Terbitkan Invoice
              </Button>
              <Button variant="secondary" onClick={() => setShowConfirmReset(true)}
                style={{ height: 38, justifyContent: 'center', gap: 8, fontSize: 12.5, width: '100%' }}>
                <RotateCcw size={13} /> Reset
              </Button>
            </>
          )}
        </div>
      </div>

      <ConfirmDialog
        isOpen={showConfirm} onClose={() => setShowConfirm(false)} onConfirm={eksekuSimpan}
        tipe="simpan" judul="Terbitkan Invoice Gudang FCL?"
        pesan="Invoice akan diterbitkan dan masuk ke Daftar Invoice."
        detail={[
          { label: 'Nomor KW',   value: '(dari server)' },
          { label: 'Nomor B/L',  value: doc?.blNomor },
          { label: 'Consignee',  value: doc?.consignee },
          { label: 'Container',  value: `${containers.length} unit` },
          { label: 'Grand Total',value: formatRupiah(kalkulasi.grandTotal) },
        ]}
      />
      <ConfirmDialog
        isOpen={showConfirmReset} onClose={() => setShowConfirmReset(false)}
        onConfirm={() => { setDoc(null); setForm(initForm); setEditableContainers([]) }}
        tipe="reset" judul="Reset form?" pesan="Dokumen yang dipilih akan dibatalkan."
      />
      <ConfirmDialog
        isOpen={!!hapusTarget} onClose={() => setHapusTarget(null)}
        onConfirm={() => handleHapus(hapusTarget)}
        tipe="hapus" judul="Hapus Dokumen Gudang?"
        pesan="Dokumen ini akan dihapus permanen dari sistem. Data invoice yang sudah terbit tidak ikut terhapus."
        detail={[
          { label: 'No. B/L',    value: hapusTarget?.blNomor   || '-' },
          { label: 'Consignee',  value: hapusTarget?.consignee || '-' },
          { label: 'Container',  value: `${hapusTarget?.containers?.length || 0} unit` },
        ]}
      />
    </div>
  )
}