import {
    BarChart3,
    AreaChart,
    PieChart,
    GanttChart,
    TableProperties,
    CreditCard,
    LayoutGrid,
    Zap,
    Layers,
    TrendingUp,
    X,
    Eye,
    EyeOff,
    Maximize2,
    Minimize2,
    MoveHorizontal,
    Minus,
} from "lucide-react";
import { Badge } from "@/Components/ui/badge";
import { Input } from "@/Components/ui/input";
import {
    PROVIDER_ICON,
    INTEGRATION_LABELS,
} from "@/Components/Dashboard/integrationIcons";
import BlockInfoTooltip from "./BlockInfoTooltip";

const TYPE_ICON = {
    kpi: LayoutGrid,
    kpi_group: Layers,
    chart: BarChart3,
    chart_area: AreaChart,
    chart_bar: BarChart3,
    chart_donut: PieChart,
    chart_combo: BarChart3,
    chart_gantt: GanttChart,
    chart_line: TrendingUp,
    table: TableProperties,
    card: CreditCard,
    header: Zap,
    drilldown: TableProperties,
    separator: Minus,
};

const TYPE_COLOR = {
    kpi: "bg-blue-500/10 text-blue-600 dark:text-blue-400",
    kpi_group: "bg-blue-500/10 text-blue-600 dark:text-blue-400",
    chart: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
    chart_line: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
    table: "bg-amber-500/10 text-amber-600 dark:text-amber-400",
    card: "bg-purple-500/10 text-purple-600 dark:text-purple-400",
    header: "bg-slate-500/10 text-slate-600 dark:text-slate-400",
    drilldown: "bg-orange-500/10 text-orange-600 dark:text-orange-400",
};

const COL_SPAN_MAP = {
    "2": "col-span-2",
    "4": "col-span-4",
    "6": "col-span-6",
    "8": "col-span-8",
    "10": "col-span-10",
    "12": "col-span-12",
};

export function sizeToColSpan(size) {
    return COL_SPAN_MAP[String(size)] || "col-span-12";
}

const SIZE_PERCENT = {
    "2": "17%",
    "4": "33%",
    "6": "50%",
    "8": "67%",
    "10": "83%",
    "12": "100%",
};

function sizeLabel(size) {
    return SIZE_PERCENT[String(size)] || `${size}col`;
}

const RESIZABLE_TYPES = new Set([
    "chart", "chart_line", "chart_area", "chart_bar", "chart_donut",
    "chart_combo", "chart_gantt", "drilldown",
]);

const TYPE_LABELS = {
    kpi: "KPI",
    kpi_group: "KPI Group",
    chart: "Grafico",
    chart_area: "Area",
    chart_bar: "Barras",
    chart_donut: "Donut",
    chart_combo: "Combo",
    chart_gantt: "Gantt",
    chart_line: "Linha",
    table: "Tabela",
    card: "Card",
    header: "Header",
    drilldown: "Drill-down",
    separator: "Separador",
};

export default function CanvasBlock({ block, onToggle, onRemove, onSizeChange, onConfigChange }) {
    const blockKey = block.instance_id ?? block.block_id;
    const effectiveType = block.chart_type || block.type;

    // Render especifico para separator: input de titulo opcional
    if (block.type === "separator") {
        return (
            <div className={[sizeToColSpan(12), "select-none"].join(" ")}>
                <div
                    className={[
                        "group rounded-lg border bg-card px-3 py-2 transition-shadow hover:shadow-sm",
                        !block.is_enabled ? "opacity-50" : "",
                    ].join(" ")}
                >
                    <div className="flex items-center gap-2">
                        <div className="flex items-center justify-center h-6 w-6 rounded shrink-0 bg-slate-500/10 text-slate-600 dark:text-slate-400">
                            <Minus className="h-3.5 w-3.5" />
                        </div>
                        <Input
                            type="text"
                            placeholder="Titulo do separador (opcional)"
                            defaultValue={block.config?.title ?? ""}
                            onBlur={(e) => onConfigChange?.(blockKey, { title: e.target.value })}
                            className="h-7 text-xs flex-1"
                        />
                        <Badge variant="secondary" className="text-[10px] shrink-0">
                            Separador
                        </Badge>
                        <button
                            type="button"
                            className="h-6 w-6 shrink-0 inline-flex items-center justify-center rounded-md hover:bg-muted/60 transition-colors"
                            onClick={() => onToggle(blockKey, !block.is_enabled)}
                            title={block.is_enabled ? "Ocultar" : "Mostrar"}
                        >
                            {block.is_enabled ? (
                                <Eye className="h-3.5 w-3.5 text-muted-foreground" />
                            ) : (
                                <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />
                            )}
                        </button>
                        <button
                            type="button"
                            className="h-6 w-6 shrink-0 inline-flex items-center justify-center rounded-md text-muted-foreground/30 hover:text-destructive hover:bg-destructive/10 transition-colors opacity-0 group-hover:opacity-100"
                            onClick={() => onRemove(blockKey)}
                            title="Remover"
                        >
                            <X className="h-3.5 w-3.5" />
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    const TypeIcon = TYPE_ICON[effectiveType] || TYPE_ICON[block.type] || LayoutGrid;
    const BadgeIcon = TYPE_ICON[effectiveType] || TYPE_ICON[block.type] || LayoutGrid;
    const typeColor = TYPE_COLOR[block.type] || TYPE_COLOR.card;
    const typeLabel = block.chart_type
        ? TYPE_LABELS[block.chart_type] || TYPE_LABELS[block.type] || block.type
        : TYPE_LABELS[block.type] || block.type;

    const size = parseInt(block.size, 10) || 12;
    const isCompact = size <= 4;
    const isResizable = RESIZABLE_TYPES.has(effectiveType) && (size === 6 || size === 12);

    if (isCompact) {
        return (
            <div className={[sizeToColSpan(size), "select-none"].join(" ")}>
                <BlockInfoTooltip block={block} side="top">
                <div
                    className={[
                        "group rounded-lg border bg-card p-2 h-full transition-shadow hover:shadow-sm",
                        !block.is_enabled ? "opacity-50" : "",
                    ].join(" ")}
                >
                    <div className="flex items-center gap-1.5">
                        <div
                            className={`flex items-center justify-center h-5 w-5 rounded shrink-0 ${typeColor}`}
                        >
                            <TypeIcon className="h-3 w-3" />
                        </div>
                        <span className="text-[13px] font-medium truncate flex-1 leading-tight">
                            {block.name}
                        </span>
                        <button
                            type="button"
                            className="h-5 w-5 shrink-0 inline-flex items-center justify-center rounded hover:bg-muted/60 transition-colors"
                            onClick={() =>
                                onToggle(blockKey, !block.is_enabled)
                            }
                        >
                            {block.is_enabled ? (
                                <Eye className="h-3 w-3 text-muted-foreground" />
                            ) : (
                                <EyeOff className="h-3 w-3 text-muted-foreground" />
                            )}
                        </button>
                        <button
                            type="button"
                            className="h-5 w-5 shrink-0 inline-flex items-center justify-center rounded text-muted-foreground/30 hover:text-destructive hover:bg-destructive/10 transition-colors opacity-0 group-hover:opacity-100"
                            onClick={() => onRemove(blockKey)}
                            title="Remover"
                        >
                            <X className="h-3 w-3" />
                        </button>
                    </div>
                    {/* Compact metadata row */}
                    <div className="flex items-center gap-1 mt-1">
                        <Badge
                            variant="secondary"
                            className="text-[8px] h-3.5 px-1 inline-flex items-center gap-0.5"
                        >
                            <BadgeIcon className="h-2.5 w-2.5" />
                            {typeLabel}
                        </Badge>
                        <Badge
                            variant="outline"
                            className="text-[8px] h-3.5 px-1 inline-flex items-center gap-0.5"
                        >
                            <MoveHorizontal className="h-2.5 w-2.5" />
                            {sizeLabel(size)}
                        </Badge>
                        {block.sources &&
                            block.sources.slice(0, 2).map((src) => {
                                const Icon = PROVIDER_ICON[src];
                                return Icon ? (
                                    <Icon
                                        key={src}
                                        size={10}
                                        className="text-muted-foreground/60"
                                    />
                                ) : null;
                            })}
                        {block.calculated && (
                            <Badge
                                variant="outline"
                                className="text-[8px] h-3.5 px-1 border-amber-500/50 text-amber-600 dark:text-amber-400"
                            >
                                calc
                            </Badge>
                        )}
                    </div>
                </div>
                </BlockInfoTooltip>
            </div>
        );
    }

    // Full-size block
    return (
        <div className={[sizeToColSpan(size), "select-none"].join(" ")}>
            <BlockInfoTooltip block={block} side="top">
            <div
                className={[
                    "group rounded-lg border bg-card p-3 space-y-1.5 h-full transition-shadow hover:shadow-sm",
                    !block.is_enabled ? "opacity-50" : "",
                ].join(" ")}
            >
                {/* Header row */}
                <div className="flex items-center gap-2">
                    <div
                        className={`flex items-center justify-center h-6 w-6 rounded shrink-0 ${typeColor}`}
                    >
                        <TypeIcon className="h-3.5 w-3.5" />
                    </div>

                    <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium leading-tight truncate">
                            {block.name}
                        </p>
                    </div>

                    <Badge
                        variant="secondary"
                        className="text-[10px] shrink-0 inline-flex items-center gap-0.5"
                    >
                        <BadgeIcon className="h-3 w-3" />
                        {typeLabel}
                    </Badge>

                    <Badge
                        variant="outline"
                        className="text-[10px] shrink-0 inline-flex items-center gap-0.5"
                    >
                        <MoveHorizontal className="h-3 w-3" />
                        {sizeLabel(size)}
                    </Badge>

                    {isResizable && (
                        <button
                            type="button"
                            className="h-6 w-6 shrink-0 inline-flex items-center justify-center rounded-md hover:bg-muted/60 transition-colors"
                            onClick={() =>
                                onSizeChange?.(blockKey, size === 12 ? 6 : 12)
                            }
                            title={size === 12 ? "Reduzir para 50%" : "Expandir para 100%"}
                        >
                            {size === 12 ? (
                                <Minimize2 className="h-3.5 w-3.5 text-muted-foreground" />
                            ) : (
                                <Maximize2 className="h-3.5 w-3.5 text-muted-foreground" />
                            )}
                        </button>
                    )}

                    <button
                        type="button"
                        className="h-6 w-6 shrink-0 inline-flex items-center justify-center rounded-md hover:bg-muted/60 transition-colors"
                        onClick={() =>
                            onToggle(blockKey, !block.is_enabled)
                        }
                    >
                        {block.is_enabled ? (
                            <Eye className="h-3.5 w-3.5 text-muted-foreground" />
                        ) : (
                            <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />
                        )}
                    </button>

                    <button
                        type="button"
                        className="h-6 w-6 shrink-0 inline-flex items-center justify-center rounded-md text-muted-foreground/30 hover:text-destructive hover:bg-destructive/10 transition-colors opacity-0 group-hover:opacity-100"
                        onClick={() => onRemove(blockKey)}
                        title="Remover do canvas"
                    >
                        <X className="h-3.5 w-3.5" />
                    </button>
                </div>

                {/* Description */}
                <p className="text-xs text-muted-foreground pl-[32px] leading-relaxed line-clamp-2">
                    {block.description}
                </p>

                {/* Sources + badges */}
                {block.sources && block.sources.length > 0 && (
                    <div className="flex items-center gap-1.5 pl-[32px]">
                        {block.sources.map((src) => {
                            const Icon = PROVIDER_ICON[src];
                            return Icon ? (
                                <span
                                    key={src}
                                    className="flex items-center gap-1 text-[10px] text-muted-foreground"
                                    title={INTEGRATION_LABELS[src] || src}
                                >
                                    <Icon size={12} />
                                </span>
                            ) : null;
                        })}
                        {block.is_combined && (
                            <Badge
                                variant="outline"
                                className="text-[9px] h-4 px-1 border-violet-500/50 text-violet-600 dark:text-violet-400"
                            >
                                combinado
                            </Badge>
                        )}
                        {block.calculated && (
                            <Badge
                                variant="outline"
                                className="text-[9px] h-4 px-1 border-amber-500/50 text-amber-600 dark:text-amber-400"
                            >
                                calc
                            </Badge>
                        )}
                    </div>
                )}
            </div>
            </BlockInfoTooltip>
        </div>
    );
}
