import { useEffect, useState } from 'react';
import { Button, Checkbox, Input, Label, TextField } from '@heroui/react';
import { PlusIcon, TrashIcon } from '@heroicons/react/24/solid';
import { FileField } from '@/Components/ui/FileField';

export interface SosmedItem {
    id: string;
    label: string;
    checked: boolean;
    link: string;
    files: string[];
}

function makeId(): string {
    return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
}

export function toSosmed(raw?: any): SosmedItem[] {
    if (!Array.isArray(raw)) {
        if (raw && typeof raw === 'object' && raw.checklist && typeof raw.checklist === 'object') {
            return Object.entries(raw.checklist).map(([key, val]) => ({
                id: key,
                label: key.replace(/_/g, ' ').toUpperCase(),
                checked: Boolean(val),
                link: '',
                files: [],
            }));
        }
        return [];
    }

    return raw.map((it) => ({
        id: it?.id ?? makeId(),
        label: it?.label ?? '',
        checked: it?.checked ?? false,
        link: it?.link ?? '',
        files: Array.isArray(it?.files) ? it.files : [],
    }));
}

function newItem(): SosmedItem {
    return { id: makeId(), label: '', checked: false, link: '', files: [] };
}

const isImage = (url: string) => /\.(png|jpe?g|gif|webp|svg)(\?.*)?$/i.test(url);

function SosmedRow({
    item,
    readOnly,
    onUpdate,
    onRemove,
}: {
    item: SosmedItem;
    readOnly?: boolean;
    onUpdate: (patch: Partial<SosmedItem>) => void;
    onRemove: () => void;
}) {
    const [label, setLabel] = useState(item.label);
    const [link, setLink] = useState(item.link);

    useEffect(() => setLabel(item.label), [item.label]);
    useEffect(() => setLink(item.link), [item.link]);

    return (
        <div className="rounded-xl border border-gray-200 bg-gray-50 p-3 sm:p-4 flex flex-col gap-3">
            <div className="flex items-center gap-2">
                <Checkbox isSelected={item.checked} isDisabled={readOnly} onChange={(v) => onUpdate({ checked: v })}>
                    <Checkbox.Content className="gap-2">
                        <Checkbox.Control>
                            <Checkbox.Indicator />
                        </Checkbox.Control>
                    </Checkbox.Content>
                </Checkbox>
                <TextField
                    value={label}
                    onChange={setLabel}
                    onBlur={() => label !== item.label && onUpdate({ label })}
                    isDisabled={readOnly}
                    fullWidth
                >
                    <Input placeholder="Nama platform, mis. Instagram, YouTube, Threads" fullWidth />
                </TextField>
                {!readOnly && (
                    <button type="button" onClick={onRemove} className="text-gray-300 hover:text-red-600 shrink-0" aria-label="Hapus">
                        <TrashIcon className="w-4 h-4" />
                    </button>
                )}
            </div>

            <TextField
                value={link}
                onChange={setLink}
                onBlur={() => link !== item.link && onUpdate({ link })}
                isDisabled={readOnly}
                fullWidth
                className="flex flex-col gap-1.5"
            >
                <Label>Link</Label>
                <Input placeholder="https://..." fullWidth />
            </TextField>

            {!readOnly ? (
                <FileField
                    label="Berkas"
                    value={item.files}
                    onChange={(files) => onUpdate({ files })}
                    folder="kegiatan/sosmed"
                    hint="Gambar atau PDF, bisa lebih dari satu"
                />
            ) : item.files.length > 0 ? (
                <div className="grid grid-cols-3 sm:grid-cols-5 gap-3">
                    {item.files.map((url, i) => (
                        <a key={url + i} href={url} target="_blank" rel="noreferrer" className="aspect-square block">
                            {isImage(url) ? (
                                <img src={url} alt="Berkas" className="w-full h-full rounded-lg object-cover border border-gray-200" />
                            ) : (
                                <span className="flex w-full h-full items-center justify-center rounded-lg border border-gray-200 bg-gray-50 text-sky-600 text-xs font-medium text-center">
                                    Buka file
                                </span>
                            )}
                        </a>
                    ))}
                </div>
            ) : (
                <span className="text-sm text-gray-400">Belum ada berkas.</span>
            )}
        </div>
    );
}

interface Props {
    value: SosmedItem[];
    onChange: (next: SosmedItem[]) => void;
    readOnly?: boolean;
}

export function SosmedChecklist({ value, onChange, readOnly }: Props) {
    const items = toSosmed(value);

    function update(id: string, patch: Partial<SosmedItem>) {
        onChange(items.map((it) => (it.id === id ? { ...it, ...patch } : it)));
    }

    function remove(id: string) {
        onChange(items.filter((it) => it.id !== id));
    }

    return (
        <div className="flex flex-col gap-3">
            {items.length === 0 && (
                <p className="text-sm text-gray-400">Belum ada platform sosmed ditambahkan.</p>
            )}

            {items.map((item) => (
                <SosmedRow key={item.id} item={item} readOnly={readOnly} onUpdate={(patch) => update(item.id, patch)} onRemove={() => remove(item.id)} />
            ))}

            {!readOnly && (
                <Button variant="outline" onPress={() => onChange([...items, newItem()])}>
                    <PlusIcon className="w-4 h-4" /> <span>Tambah Platform</span>
                </Button>
            )}
        </div>
    );
}
