import { useState } from 'react';
import Offcanvas from '../../components/Offcanvas';
import CircularTab from '../../components/CircularTab';
import Button from '../../components/Buttons';
import { Product } from '../../utils/product';
import Select from 'react-select';
import IconPlus from '../../components/Icon/IconPlus';
import IconMinus from '../../components/Icon/IconMinus';
import IconRefresh from '../../components/Icon/IconRefresh';
import IconX from '../../components/Icon/IconX';
import IconTrendingUp from '../../components/Icon/IconTrendingUp';
import IconShoppingBag from '../../components/Icon/IconShoppingBag';
import IconRestore from '../../components/Icon/IconRestore';
import AddProductPanel from './AddProduct';

export type SalesOrder = {
    id: string;
    date: string;
    customerName: string;
    amount: number;
    status: string;
    qty: number;
    channel: Channel;
};


interface Props {
    product: Product;
    isOpen: boolean;
    onClose: () => void;
    setMode: (m: "add" | "edit") => void;
    setEditProduct: (p: Product) => void;
    setOpenAddProduct: (v: boolean) => void;
}
/* ── Channel pill colours ───────────────────────────────── */
export type Channel = "instagram" | "web" | "whatsapp";

const channelOptions = [
    { value: "instagram", label: "INSTAGRAM Stores" },
    { value: "web", label: "WEB Stores" },
    { value: "whatsapp", label: "WHATSAPP Stores" },
];

const typeOptions = [
    { value: "restock", label: "Restock / Add In (+)" },
    { value: "sale", label: "Sale Deduct (-)" },
    { value: "adjustment", label: "Manual Adjustment" },
];

const channelBadge: Record<Channel, string> = {
    instagram: "bg-pink-50 text-pink-600 border-pink-100",
    web: "bg-indigo-50 text-indigo-600 border-indigo-100",
    whatsapp: "bg-emerald-50 text-emerald-600 border-emerald-100",
};


const inputCls =
    'w-full border border-[#ECE2D2] bg-[#FBF6ED] rounded-[10px] px-[14px] py-[10px] text-[14px] text-[#3B2F28] outline-none box-border focus:border-[#CF8F42] focus:ring-1 focus:ring-[#CF8F42] transition';


const selectStyles = {
    control: (base: any, state: any) => ({
        ...base,
        transition: "all 0.2s ease",
        backgroundColor: "#FBF6ED",
        borderColor: state.isFocused ? "#CF8F42" : "#ECE2D2",
        boxShadow: state.isFocused
            ? "0 0 0 3px rgba(207, 143, 66, 0.15)"
            : "none",
        borderRadius: "10px",
        padding: "2px 6px",
        minHeight: "42px",
        fontSize: "14px",
        color: "#3B2F28",
        "&:hover": {
            borderColor: "#CF8F42",
        },
    }),

    valueContainer: (base: any) => ({
        ...base,
        padding: "2px 6px",
    }),

    input: (base: any) => ({
        ...base,
        color: "#3B2F28",
    }),

    placeholder: (base: any) => ({
        ...base,
        color: "#9A8F86",
        fontSize: "14px",
    }),

    singleValue: (base: any) => ({
        ...base,
        color: "#3B2F28",
        fontSize: "14px",
    }),

    menu: (base: any) => ({
        ...base,
        borderRadius: "10px",
        overflow: "hidden",
        marginTop: 6,
        backgroundColor: "#ffffff",
        border: "1px solid #ECE2D2",
    }),

    option: (base: any, state: any) => ({
        ...base,
        fontSize: "14px",
        backgroundColor: state.isFocused
            ? "#FBF6ED"
            : state.isSelected
                ? "#F3E3C7"
                : "#fff",
        color: "#3B2F28",
        cursor: "pointer",
    }),

    dropdownIndicator: (base: any) => ({
        ...base,
        color: "#3B2F28",
        "&:hover": {
            color: "#CF8F42",
        },
    }),

    indicatorSeparator: () => ({
        display: "none",
    }),
};

const ProfileTab = ({ product }: { product: Product }) => {
    const total =
        product.stock.instagram +
        product.stock.web +
        product.stock.whatsapp;

    const unitPrice = product.price;

    const unitsSold = product.orders?.reduce((sum, o) => sum + (o.qty ?? 0), 0) ?? 0;

    const grossRevenue = product.orders?.reduce((sum, o) => sum + o.amount, 0) ?? 0;

    const stockData = [
        { key: 'instagram', label: 'Instagram', color: 'bg-pink-500' },
        { key: 'web', label: 'Web', color: 'bg-indigo-600' },
        { key: 'whatsapp', label: 'WhatsApp', color: 'bg-emerald-500' },
    ] as const;

    return (
        <div className="space-y-6">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">

                <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-200">
                    <span className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                        Unit Price
                    </span>
                    <span className="text-base font-extrabold text-slate-900 block mt-1">
                        ₹{unitPrice.toLocaleString('en-IN')}
                    </span>
                </div>

                <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-200">
                    <span className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                        Units Sold
                    </span>
                    <span className="text-base font-extrabold text-emerald-600 block mt-1">
                        {unitsSold} units
                    </span>
                </div>

                <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-200">
                    <span className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                        Gross Revenue
                    </span>
                    <span className="text-base font-extrabold text-amber-600 block mt-1">
                        ₹{grossRevenue.toLocaleString('en-IN')}
                    </span>
                </div>

                <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-200">
                    <span className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                        Current Stock
                    </span>
                    <span className="text-base font-extrabold text-red-600 block mt-1">
                        {total} Left
                    </span>
                </div>
            </div>

            {/* ── Channel Allocation Split ─────────────────── */}
            <div className="bg-white border border-slate-200 rounded-2xl p-5 space-y-4">

                <div className="flex items-center justify-between">
                    <h3 className="text-xs font-bold uppercase tracking-wider text-slate-900">
                        Channel Allocation Split
                    </h3>
                    <span className="text-[10px] font-bold text-slate-400 uppercase">
                        Total: {total} units
                    </span>
                </div>

                {/* Progress Bar */}
                <div className="h-4 rounded-full flex overflow-hidden bg-slate-100">
                    {stockData.map((ch) => {
                        const value = product.stock[ch.key];
                        const percent = total ? (value / total) * 100 : 0;

                        return (
                            <div
                                key={ch.key}
                                className={`${ch.color} h-full transition-all duration-500`}
                                style={{ width: `${percent}%` }}
                                title={`${ch.label}: ${value} units`}
                            />
                        );
                    })}
                </div>

                {/* Breakdown */}
                <div className="grid grid-cols-3 gap-2 pt-2 text-xs">
                    {stockData.map((ch) => (
                        <div
                            key={ch.key}
                            className="flex flex-col p-2 bg-slate-50 rounded-lg"
                        >
                            <span className="flex items-center gap-1.5 text-[9px] font-bold uppercase text-slate-500">
                                <span className={`w-2 h-2 rounded-full ${ch.color}`} />
                                {ch.label}
                            </span>

                            <span className="text-sm font-extrabold mt-1 text-slate-900">
                                {product.stock[ch.key]} units
                            </span>
                        </div>
                    ))}
                </div>
            </div>

            {/* ── Insight Box ─────────────────────────────── */}
            <div className="bg-amber-50 border border-amber-200 rounded-2xl p-4 flex gap-3">
                <div className="text-amber-600 mt-0.5">⚠️</div>

                <div className="space-y-1">
                    <h4 className="text-xs font-bold uppercase tracking-wider text-amber-700">
                        Warehouse Health Insight
                    </h4>
                    <p className="text-xs text-slate-600 leading-relaxed">
                        Operating at optimal capacity. Stock distribution is balanced across channels
                        with stable turnover velocity.
                    </p>
                </div>
            </div>

            {/* ── SKU Metadata ────────────────────────────── */}
            <div className="bg-slate-50 border border-slate-200 rounded-2xl p-5 space-y-4">

                <h4 className="text-xs font-bold uppercase tracking-wider text-slate-800">
                    SKU Metadata Specs
                </h4>

                <div className="grid grid-cols-2 gap-4 text-xs">

                    <div>
                        <span className="block text-[9px] font-bold text-slate-400 uppercase">
                            Category Class
                        </span>
                        <span className="font-bold text-slate-900">
                            {product.category}
                        </span>
                    </div>

                    <div>
                        <span className="block text-[9px] font-bold text-slate-400 uppercase">
                            Retail Price Tag
                        </span>
                        <span className="font-bold text-slate-900">
                            ₹{unitPrice.toLocaleString('en-IN')}
                        </span>
                    </div>

                    <div>
                        <span className="block text-[9px] font-bold text-slate-400 uppercase">
                            Assigned Stores
                        </span>
                        <span className="font-bold text-slate-900 capitalize">
                            instagram, web, whatsapp
                        </span>
                    </div>

                    <div>
                        <span className="block text-[9px] font-bold text-slate-400 uppercase">
                            Pending Delivery Allocation
                        </span>
                        <span className="font-bold text-amber-600">
                            1 units
                        </span>
                    </div>

                </div>
            </div>

        </div>
    );
};

const OrdersTab = ({ orders }: { orders: SalesOrder[] }) => {
    return (
        <div className="space-y-4 fade-in animate-fade-in">
            <div className="flex items-center justify-between text-xs px-1">
                <span className="font-bold text-slate-500 uppercase tracking-wider">
                    Linked Client orders containing this product
                </span>
                <span className="text-[10px] bg-slate-100 text-slate-600 font-extrabold px-2 py-0.5 rounded uppercase font-mono">
                    Count: {orders.length}
                </span>
            </div>

            <div className="space-y-2.5 max-h-[500px] overflow-y-auto pr-1">
                {orders.length === 0 && (
                    <p className="text-xs text-slate-400 text-center py-8">
                        No orders found.
                    </p>
                )}
                {orders.map((o) => (
                    <div
                        key={o.id}
                        className="bg-white border border-slate-200 rounded-xl p-4 flex items-center justify-between
                       hover:shadow-sm hover:border-amber-400 transition-all"
                    >
                        <div className="space-y-1">

                            {/* Top row */}
                            <div className="flex items-center gap-2">

                                <span className="font-black text-xs text-slate-900">
                                    {o.id}
                                </span>

                                <span className="text-[10px] uppercase font-bold text-slate-400">
                                    {o.date}
                                </span>
                                <span
                                    className={`text-[9px] font-extrabold uppercase px-1.5 py-0.5 rounded border
                    ${o.channel === 'instagram'
                                            ? 'bg-pink-50 text-pink-600 border-pink-100'
                                            : o.channel === 'web'
                                                ? 'bg-indigo-50 text-indigo-600 border-indigo-100'
                                                : 'bg-emerald-50 text-emerald-600 border-emerald-100'
                                        }`}
                                >
                                    {o.channel}
                                </span>
                            </div>

                            <p className="text-xs font-bold text-slate-700">
                                Customer: {o.customerName}
                            </p>

                            {/* Purchase info */}
                            <p className="text-[11px] text-slate-500">
                                Purchased:{' '}
                                <span className="font-bold text-slate-900">
                                    {o.qty ?? 1} units
                                </span>{' '}
                                at ₹{o.amount.toLocaleString('en-IN')}
                            </p>
                        </div>

                        {/* RIGHT SECTION */}
                        <div className="flex flex-col items-end gap-2 shrink-0">

                            {/* Status badge */}
                            <span
                                className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border
                  ${o.status === 'Delivered'
                                        ? 'bg-emerald-50 text-emerald-700 border-emerald-200'
                                        : o.status === 'Packed'
                                            ? 'bg-purple-50 text-purple-700 border-purple-200'
                                            : 'bg-amber-50 text-amber-700 border-amber-200'
                                    }`}
                            >
                                {o.status}
                            </span>

                            {/* Action */}
                            <button
                                type="button"
                                className="text-[10px] text-amber-600 font-bold flex items-center gap-1 hover:underline active:scale-95"
                                onClick={() => console.log('Open order:', o.id)}
                            >
                                Open Order
                                <svg
                                    width="10"
                                    height="10"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    strokeWidth="2"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                >
                                    <path d="m9 18 6-6-6-6" />
                                </svg>
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};



/* ── Main component ──────────────────────────────────────── */
const ViewInventory = ({ product, isOpen, onClose }: Props) => {
    const [openAddProduct, setOpenAddProduct] = useState(false);
    const [mode, setMode] = useState<"add" | "edit">("add");
    const [editProduct, setEditProduct] = useState<Product | null>(null);


    const header = (
        <div style={{ margin: '-18px -20px 0', borderRadius: '16px 16px 0 0', overflow: 'hidden', borderBottom: '0px !important' }}>
            <div className="bg-[#451A03] px-6 py-6 text-amber-100 flex items-center justify-between">
                <div className="flex items-center gap-3">
                    <div className="w-14 h-14 rounded-xl overflow-hidden bg-white/10 border border-white/10 shrink-0">
                        {product.image ? (
                            <img src={product.image} alt={product.name} className="w-full h-full object-cover" referrerPolicy="no-referrer" />
                        ) : (
                            <div className="w-full h-full flex items-center justify-center text-amber-200 text-lg font-bold">
                                {product.name[0]}
                            </div>
                        )}
                    </div>
                    <div>
                        <span className="text-[10px] bg-amber-400 text-slate-950 font-extrabold uppercase px-2 py-0.5 rounded tracking-widest">
                            Product Profile
                        </span>
                        <h2 className="text-base font-bold text-white mt-0.5 line-clamp-1">{product.name}</h2>
                        <p className="text-[11px] text-amber-100/70 font-mono tracking-wider">
                            SKU Code: {product.sku} • {product.category}
                        </p>
                    </div>
                </div>
                <button onClick={onClose}
                    className="p-1.5 rounded-full hover:bg-white/10 text-amber-200 hover:text-white transition-all cursor-pointer">
                    <IconX />
                </button>
            </div>
        </div>
    );


    return (
        <>
            <Offcanvas
                isOpen={isOpen}
                onClose={onClose}
                width={672}
                header={header}
            >
                <ProfileTab product={product} />
            </Offcanvas>

            <AddProductPanel
                open={openAddProduct}
                setOpen={setOpenAddProduct}
                mode={mode}
                editData={editProduct}
            />
        </>
    );
};

export default ViewInventory;