import type { RequestPayload } from '@inertiajs/core';
import { router, usePage } from '@inertiajs/react';
import { Plus, Save, X } from 'lucide-react';
import { useState } from 'react';
import { Button } from '@/components/ui/button';

interface Block {
    type: string;
    align?: string;
    de?: string | null;
    fr?: string | null;
    it?: string | null;
}

/*
 * PCM round 10 — CMS page editor (BR CMS): trilingual text blocks with
 * alignment. Admin-only.
 */
export function CmsShowView({
    page,
}: {
    page: {
        id: number;
        slug: string;
        brand_code: string;
        name_de: string;
        active: boolean;
        decommission_at: string | null;
        blocks: Block[];
    };
}) {
    const canEdit = usePage().props.auth.can.edit_catalog;
    const [blocks, setBlocks] = useState<Block[]>(page.blocks);

    const setBlock = (index: number, patch: Partial<Block>) => {
        setBlocks((prev) =>
            prev.map((b, i) => (i === index ? { ...b, ...patch } : b)),
        );
    };

    const save = () => {
        router.patch(
            `/cms/pages/${page.id}`,
            { blocks: JSON.stringify(blocks) },
            { preserveScroll: true },
        );
    };

    return (
        <div className="custom-scroll flex-1 overflow-y-auto">
            <header className="flex flex-wrap items-center justify-between gap-3 border-b border-gray-100 bg-white p-5">
                <div>
                    <h1 className="text-lg font-bold text-astara-purple">
                        {page.name_de}
                    </h1>
                    <p className="font-mono text-[10px] text-gray-400">
                        {page.slug}
                    </p>
                </div>
                <Button size="sm" onClick={save}>
                    <Save size={14} />
                    Save
                </Button>
            </header>

            <div className="p-4 md:p-6">
                <div className="mx-auto max-w-3xl space-y-4 pb-12">
                    <p className="text-[10px] font-bold tracking-widest text-gray-400 uppercase">
                        Content blocks (DE / FR / IT)
                    </p>
                    {(canEdit ? blocks : []).map((block, index) => (
                        <section
                            key={index}
                            className="rounded-xl border border-[rgba(30,25,50,0.06)] bg-white p-4 shadow-sm"
                        >
                            <div className="mb-2 flex items-center justify-between">
                                <span className="text-[9px] font-bold text-gray-400">
                                    Block {index + 1}
                                </span>
                                <button
                                    type="button"
                                    onClick={() =>
                                        setBlocks((prev) =>
                                            prev.filter((_, i) => i !== index),
                                        )
                                    }
                                    aria-label={`Delete block ${index + 1}`}
                                    className="cursor-pointer rounded-md p-1 text-gray-300 hover:bg-red-50 hover:text-red-600 focus-visible:ring-2 focus-visible:ring-red-400 focus-visible:outline-none"
                                >
                                    <X size={14} />
                                </button>
                            </div>
                            <textarea
                                rows={2}
                                placeholder="DE"
                                value={block.de ?? ''}
                                onChange={(e) =>
                                    setBlock(index, { de: e.target.value })
                                }
                                className="mb-2 w-full resize-y rounded-md border border-slate-200 p-2 text-[11px]"
                            />
                            <textarea
                                rows={2}
                                placeholder="FR"
                                value={block.fr ?? ''}
                                onChange={(e) =>
                                    setBlock(index, { fr: e.target.value })
                                }
                                className="mb-2 w-full resize-y rounded-md border border-slate-200 p-2 text-[11px]"
                            />
                            <textarea
                                rows={2}
                                placeholder="IT"
                                value={block.it ?? ''}
                                onChange={(e) =>
                                    setBlock(index, { it: e.target.value })
                                }
                                className="w-full resize-y rounded-md border border-slate-200 p-2 text-[11px]"
                            />
                        </section>
                    ))}

                    {!canEdit && blocks.length === 0 && (
                        <p className="text-[11px] text-gray-400 italic">
                            No content blocks.
                        </p>
                    )}

                    {blocks.length === 0 && !canEdit && null}
                </div>
            </div>
        </div>
    );
}
