import { Plus, RefreshCw, Trash2 } from 'lucide-react';
import { useState } from 'react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

interface AttributeValue {
    id: number;
    value: string;
    slug: string;
}

interface Attribute {
    id: number;
    name: string;
    slug: string;
    values: AttributeValue[];
}

export interface VariantRow {
    variant_name: string;
    sku: string;
    price: string;
    stock_qty: string;
    attribute_value_ids: number[];
}

interface Props {
    attributes: Attribute[];
    variants: VariantRow[];
    onChange: (variants: VariantRow[]) => void;
    basePrice?: string;
}

function cartesian(arrays: AttributeValue[][]): AttributeValue[][] {
    if (arrays.length === 0) return [];
    return arrays.reduce<AttributeValue[][]>(
        (acc, cur) => acc.flatMap((a) => cur.map((b) => [...a, b])),
        [[]],
    );
}

export default function VariantBuilder({ attributes, variants, onChange, basePrice = '' }: Props) {
    const [selectedAttrs, setSelectedAttrs] = useState<number[]>([]);

    const toggleAttr = (id: number) => {
        setSelectedAttrs((prev) => (prev.includes(id) ? prev.filter((a) => a !== id) : [...prev, id]));
    };

    const generateCombinations = () => {
        const chosen = attributes.filter((a) => selectedAttrs.includes(a.id));
        if (chosen.length === 0) return;
        const combos = cartesian(chosen.map((a) => a.values));
        const rows: VariantRow[] = combos.map((combo) => ({
            variant_name: combo.map((v) => v.value).join(' / '),
            sku: '',
            price: basePrice,
            stock_qty: '0',
            attribute_value_ids: combo.map((v) => v.id),
        }));
        onChange(rows);
    };

    const updateRow = (idx: number, field: keyof VariantRow, value: string) => {
        const updated = variants.map((row, i) =>
            i === idx ? { ...row, [field]: value } : row,
        );
        onChange(updated);
    };

    const removeRow = (idx: number) => {
        onChange(variants.filter((_, i) => i !== idx));
    };

    const addEmpty = () => {
        onChange([
            ...variants,
            { variant_name: '', sku: '', price: basePrice, stock_qty: '0', attribute_value_ids: [] },
        ]);
    };

    return (
        <div className="space-y-4">
            {/* Attribute selector */}
            <div>
                <Label className="mb-2 block text-sm font-medium text-slate-700">Select attributes to combine</Label>
                <div className="flex flex-wrap gap-2">
                    {attributes.map((attr) => (
                        <button
                            key={attr.id}
                            type="button"
                            onClick={() => toggleAttr(attr.id)}
                            className={`rounded-full border px-3 py-1 text-sm font-medium transition-all ${
                                selectedAttrs.includes(attr.id)
                                    ? 'border-indigo-500 bg-indigo-600 text-white'
                                    : 'border-slate-200 bg-slate-50 text-slate-700 hover:border-indigo-300 hover:bg-indigo-50'
                            }`}
                        >
                            {attr.name}
                            {selectedAttrs.includes(attr.id) && (
                                <span className="ml-1.5 text-xs opacity-80">({attr.values.length})</span>
                            )}
                        </button>
                    ))}
                    {attributes.length === 0 && (
                        <p className="text-sm text-slate-400">
                            No attributes yet.{' '}
                            <a href="/admin/attributes" target="_blank" className="text-indigo-600 hover:underline">
                                Add attributes first →
                            </a>
                        </p>
                    )}
                </div>
            </div>

            {/* Generate button */}
            {selectedAttrs.length > 0 && (
                <Button type="button" variant="outline" size="sm" onClick={generateCombinations} className="gap-1.5">
                    <RefreshCw size={14} /> Generate {cartesian(attributes.filter((a) => selectedAttrs.includes(a.id)).map((a) => a.values)).length} combinations
                </Button>
            )}

            {/* Variant table */}
            {variants.length > 0 && (
                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b text-xs text-slate-500">
                                <th className="pb-2 text-left font-medium">Variant</th>
                                <th className="pb-2 text-left font-medium">SKU</th>
                                <th className="pb-2 text-left font-medium">Price (৳)</th>
                                <th className="pb-2 text-left font-medium">Stock</th>
                                <th className="pb-2" />
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {variants.map((row, idx) => (
                                <tr key={idx}>
                                    <td className="py-2 pr-2">
                                        <Input
                                            value={row.variant_name}
                                            onChange={(e) => updateRow(idx, 'variant_name', e.target.value)}
                                            placeholder="e.g. Red / Large"
                                            className="h-8 text-xs"
                                        />
                                    </td>
                                    <td className="py-2 pr-2">
                                        <Input
                                            value={row.sku}
                                            onChange={(e) => updateRow(idx, 'sku', e.target.value)}
                                            placeholder="Auto"
                                            className="h-8 text-xs"
                                        />
                                    </td>
                                    <td className="py-2 pr-2">
                                        <Input
                                            type="number"
                                            step="0.01"
                                            value={row.price}
                                            onChange={(e) => updateRow(idx, 'price', e.target.value)}
                                            className="h-8 w-24 text-xs"
                                        />
                                    </td>
                                    <td className="py-2 pr-2">
                                        <Input
                                            type="number"
                                            value={row.stock_qty}
                                            onChange={(e) => updateRow(idx, 'stock_qty', e.target.value)}
                                            className="h-8 w-20 text-xs"
                                        />
                                    </td>
                                    <td className="py-2">
                                        <button
                                            type="button"
                                            onClick={() => removeRow(idx)}
                                            className="text-slate-300 hover:text-red-500 transition-colors"
                                        >
                                            <Trash2 size={14} />
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            <button
                type="button"
                onClick={addEmpty}
                className="flex items-center gap-1.5 text-xs text-indigo-600 hover:text-indigo-800"
            >
                <Plus size={13} /> Add variant manually
            </button>
        </div>
    );
}
