import React from 'react';
import { Package, ArrowRight, History } from 'lucide-react';
import TactileRadialGauge from '@/Components/UI/TactileRadialGauge';
import StatusBadge from '@/Components/UI/StatusBadge';
import Button from '@/Components/UI/Button';
import SupplierShelfRailList from '@/Components/Supplier/SupplierShelfRailList';

/**
 * SupplierShelfHealthDial
 * 
 * Apple HIG adaptive shelf stock & sell-through telemetry card:
 * - Konsinyasi Berkala (isDaily = false): Focuses on shelf availability.
 *   Low remaining stock (< 35%) triggers alert (Rose/Danger - needs restock).
 * - Konsinyasi Harian (isDaily = true): 3-Stage Contextual Lifecycle:
 *   1. STANDBY: Pagi hari / belum ada pasokan masuk hari ini (Calm slate, no false red alarm).
 *   2. ACTIVE: Pasokan hari ini sedang aktif di rak & kasir POS (Live sell-through gauge/rails).
 *   3. SETTLED: Rekonsiliasi & closing shift selesai dicairkan (Clear daily completion card).
 */
export default function SupplierShelfHealthDial({
    currentStock = 0,
    targetCapacity = 80,
    totalSKU = 0,
    lowStockCount = 0,
    outOfStockCount = 0,
    products = [],
    productsHref = '/supplier/products',
    isDaily = false,
    soldCount = 0,
    dailyLifecycleState = null,
    dailySession = null,
    className = '',
}) {
    const isMultiProduct = Array.isArray(products) && products.length > 1;
    const effectiveTotalSKU = totalSKU || (products?.length ?? 0);

    const effectiveCapacity = targetCapacity > 0 ? targetCapacity : Math.max(currentStock, 1);
    const effectiveSold = soldCount > 0 ? soldCount : Math.max(0, effectiveCapacity - currentStock);

    const saturationPct = effectiveCapacity > 0 
        ? Math.min(100, Math.round((currentStock / effectiveCapacity) * 100)) 
        : 0;

    const soldPct = effectiveCapacity > 0 
        ? Math.min(100, Math.round((effectiveSold / effectiveCapacity) * 100)) 
        : 0;

    // Periodic Shelf Logic (Shelf Availability)
    const getShelfHealthConfig = (pct) => {
        if (pct >= 75) {
            return { color: 'emerald', status: 'AKTIF', statusLabel: 'Stok Melimpah' };
        }
        if (pct >= 35) {
            return { color: 'amber', status: 'WARNING', statusLabel: 'Stok Menipis' };
        }
        return { color: 'rose', status: 'DANGER', statusLabel: 'Stok Kritis' };
    };

    // Daily Consignment Logic (Sell-Through Velocity: more sold -> greener)
    const getDailyHealthConfig = (pct, stock, sold, cap) => {
        if ((cap > 0 && sold >= cap) || (stock <= 0 && sold > 0)) {
            return { color: 'emerald', status: 'AKTIF', statusLabel: 'Ludes Terjual 🎉' };
        }
        if (pct >= 75) {
            return { color: 'emerald', status: 'AKTIF', statusLabel: 'Hampir Ludes' };
        }
        if (pct >= 35) {
            return { color: 'amber', status: 'WARNING', statusLabel: 'Terjual Sebagian' };
        }
        return { color: 'rose', status: 'DANGER', statusLabel: 'Belum Banyak Laku' };
    };

    const isStandby = isDaily && dailyLifecycleState === 'STANDBY';
    const isSettled = isDaily && dailyLifecycleState === 'SETTLED';

    // In standby, benchmark against the previous batch capacity if available
    const displayCapacity = isStandby && dailySession?.last_batch?.total_dropped > 0
        ? dailySession.last_batch.total_dropped
        : effectiveCapacity;

    const config = isDaily
        ? (isStandby
            ? { color: 'slate', status: 'NEUTRAL', statusLabel: 'Menunggu Pasokan' }
            : isSettled
                ? { color: 'emerald', status: 'AKTIF', statusLabel: 'Selesai Direkonsiliasi' }
                : getDailyHealthConfig(soldPct, currentStock, effectiveSold, displayCapacity))
        : getShelfHealthConfig(saturationPct);

    return (
        <div className={`bg-white rounded-3xl border border-slate-200/80 shadow-2xs p-6 flex flex-col justify-between ${className}`}>
            <div>
                {/* Header */}
                <div className="flex items-center justify-between pb-3 mb-4 border-b border-slate-100">
                    <div className="flex items-center gap-2">
                        <Package className="w-4 h-4 text-[#1F6376]" />
                        <h3 className="text-sm font-bold text-slate-900 tracking-tight">
                            {isDaily ? 'Laju Keterjualan Pasokan' : 'Ketersediaan Stok di Rak'}
                        </h3>
                    </div>

                    <StatusBadge variant="tactile" status={config.status} dot={!isStandby}>
                        {config.statusLabel}
                    </StatusBadge>
                </div>

                {/* Body: Persistent Tactile Speedometer / Multi-Rail HUD (Zero Layout Shift) */}
                {!isMultiProduct ? (
                    <div className="py-1">
                        <TactileRadialGauge
                            type="arch"
                            size="md"
                            color={config.color}
                            value={isDaily ? (isStandby ? 0 : soldPct) : saturationPct}
                            max={100}
                            valueSuffix="%"
                            label={isDaily ? "Laju Terjual" : "Kapasitas Rak"}
                            sublabel={
                                isDaily
                                    ? (isStandby
                                        ? `0 / ${displayCapacity} pcs`
                                        : `${effectiveSold} / ${displayCapacity} pcs`)
                                    : `${currentStock} / ${displayCapacity} pcs`
                            }
                            recessed={true}
                        />
                    </div>
                ) : (
                    <SupplierShelfRailList
                        products={products}
                        isDaily={isDaily}
                        isStandby={isStandby}
                        maxDisplay={4}
                    />
                )}

                {/* Telemetry Breakdown Strip */}
                {isDaily ? (
                    <div className="grid grid-cols-3 gap-2 mt-4 p-3 bg-slate-50/80 rounded-2xl border border-slate-200/60 text-center">
                        <div>
                            <span className="text-[10px] text-slate-400 font-semibold uppercase block">
                                {isStandby ? 'Target Pasokan' : 'Pasokan'}
                            </span>
                            <span className="text-sm font-black text-slate-900 font-tabular">
                                {displayCapacity} pcs
                            </span>
                        </div>
                        <div className="border-x border-slate-200/60">
                            <span className="text-[10px] text-slate-400 font-semibold uppercase block">Terjual</span>
                            <span className={`text-sm font-black font-tabular ${!isStandby && effectiveSold >= displayCapacity && displayCapacity > 0 ? 'text-emerald-600' : isStandby ? 'text-slate-400' : 'text-[#1F6376]'}`}>
                                {isStandby ? 0 : effectiveSold} pcs
                            </span>
                        </div>
                        <div>
                            <span className="text-[10px] text-slate-400 font-semibold uppercase block">Sisa di Rak</span>
                            <span className={`text-sm font-black font-tabular ${isStandby ? 'text-slate-400' : currentStock <= 0 ? 'text-emerald-600' : 'text-slate-900'}`}>
                                {isStandby ? 0 : currentStock} pcs
                            </span>
                        </div>
                    </div>
                ) : (
                    <div className="grid grid-cols-3 gap-2 mt-4 p-3 bg-slate-50/80 rounded-2xl border border-slate-200/60 text-center">
                        <div>
                            <span className="text-[10px] text-slate-400 font-semibold uppercase block">Aktif</span>
                            <span className="text-sm font-black text-slate-900 font-tabular">{effectiveTotalSKU} SKU</span>
                        </div>
                        <div className="border-x border-slate-200/60">
                            <span className="text-[10px] text-slate-400 font-semibold uppercase block">Unit di Rak</span>
                            <span className="text-sm font-black text-[#1F6376] font-tabular">{currentStock} pcs</span>
                        </div>
                        <div>
                            <span className="text-[10px] text-slate-400 font-semibold uppercase block">Habis</span>
                            <span className={`text-sm font-black font-tabular ${outOfStockCount > 0 ? 'text-rose-600' : 'text-slate-900'}`}>
                                {outOfStockCount} SKU
                            </span>
                        </div>
                    </div>
                )}

                {/* Contextual Previous Session History (Apple HIG glanceable) */}
                {isDaily && dailySession?.last_batch && (
                    <div className="mt-3 p-3 bg-slate-50/80 rounded-2xl border border-slate-200/60 flex flex-col sm:flex-row sm:items-center justify-between gap-1.5 text-xs">
                        <div className="flex items-center gap-2 text-slate-500 min-w-0 truncate">
                            <History className="w-4 h-4 text-slate-400 shrink-0" />
                            <span className="truncate">Pasokan Terakhir ({dailySession.last_batch.date_formatted}):</span>
                        </div>
                        <div className="font-bold text-slate-900 font-tabular shrink-0 flex items-center gap-1.5">
                            <span>{dailySession.last_batch.total_sold} / {dailySession.last_batch.total_dropped} pcs terjual</span>
                            {dailySession.last_batch.is_settled && (
                                <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-800">
                                    Dicairkan ✓
                                </span>
                            )}
                        </div>
                    </div>
                )}
            </div>

            {/* Footer Action - Clean without jargon */}
            <div className="pt-4 mt-4 border-t border-slate-100 flex items-center justify-end">
                <Button
                    variant="ghost"
                    size="xs"
                    href={productsHref}
                    icon={ArrowRight}
                    iconPosition="right"
                >
                    {isDaily ? 'Rincian Produk' : 'Kelola Stok'}
                </Button>
            </div>
        </div>
    );
}
