import { ArrowDown, ArrowUp, Plus, Trash2 } from 'lucide-react';
import { useId, useState } from 'react';
import type { ReactNode } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { moveItem, removeAt, replaceAt } from '@/lib/lists';
import type { FormErrors } from '@/types';

type ListProps<T> = {
    /** Field path of the list; errors are read from `${name}.${index}…`. */
    name: string;
    label: string;
    items: T[];
    onChange: (items: T[]) => void;
    errors: FormErrors;
    /** What one entry is called: "Paragraf" → "Paragraf ekle", "Paragraf 2". */
    itemLabel: string;
    hint?: ReactNode;
    /** Language of the texts, for spell checking. */
    lang?: string;
};

type FrameProps<T> = Pick<
    ListProps<T>,
    'name' | 'label' | 'items' | 'onChange' | 'errors' | 'itemLabel' | 'hint'
> & {
    /** A fresh, empty entry. */
    blank: T;
    /** Renders the inputs of one entry; `fresh` asks to focus the first one. */
    children: (item: T, index: number, fresh: boolean) => ReactNode;
};

/**
 * Shared frame of the list editors: numbering, the add / remove / move up /
 * move down controls and the empty state. Entries are identified by their
 * position, which is all the controlled inputs need.
 */
function ListFrame<T>({
    name,
    label,
    items,
    onChange,
    errors,
    itemLabel,
    hint,
    blank,
    children,
}: FrameProps<T>) {
    const labelId = useId();
    // Position of the entry that was just added, so it can take focus.
    const [added, setAdded] = useState<number | null>(null);

    const add = (): void => {
        setAdded(items.length);
        onChange([...items, blank]);
    };

    return (
        <div
            role="group"
            aria-labelledby={labelId}
            className="grid grid-cols-1 gap-3"
        >
            <div className="grid grid-cols-1 gap-1">
                <span id={labelId} className="text-sm font-medium">
                    {label}
                </span>
                {hint && (
                    <p className="text-xs text-muted-foreground">{hint}</p>
                )}
            </div>

            {items.length === 0 ? (
                <p className="rounded-md border border-dashed px-3 py-4 text-center text-sm text-muted-foreground">
                    Henüz eklenmedi.
                </p>
            ) : (
                <ol className="grid grid-cols-1 gap-3">
                    {items.map((item, index) => (
                        <li key={index} className="flex items-start gap-2">
                            <span
                                aria-hidden="true"
                                className="mt-2 w-5 shrink-0 text-right text-xs text-muted-foreground tabular-nums"
                            >
                                {index + 1}.
                            </span>

                            <div className="grid min-w-0 flex-1 grid-cols-1 gap-2">
                                {children(item, index, index === added)}
                            </div>

                            <div className="flex shrink-0 flex-col sm:flex-row">
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="size-8"
                                    disabled={index === 0}
                                    onClick={() =>
                                        onChange(
                                            moveItem(items, index, index - 1),
                                        )
                                    }
                                >
                                    <ArrowUp />
                                    <span className="sr-only">
                                        {itemLabel} {index + 1}: yukarı taşı
                                    </span>
                                </Button>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="size-8"
                                    disabled={index === items.length - 1}
                                    onClick={() =>
                                        onChange(
                                            moveItem(items, index, index + 1),
                                        )
                                    }
                                >
                                    <ArrowDown />
                                    <span className="sr-only">
                                        {itemLabel} {index + 1}: aşağı taşı
                                    </span>
                                </Button>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="size-8 text-muted-foreground hover:text-red-600"
                                    onClick={() =>
                                        onChange(removeAt(items, index))
                                    }
                                >
                                    <Trash2 />
                                    <span className="sr-only">
                                        {itemLabel} {index + 1}: sil
                                    </span>
                                </Button>
                            </div>
                        </li>
                    ))}
                </ol>
            )}

            <div>
                <Button type="button" variant="outline" size="sm" onClick={add}>
                    <Plus />
                    {itemLabel} ekle
                </Button>
            </div>

            <InputError message={errors[name]} />
        </div>
    );
}

type StringListProps = ListProps<string> & {
    /** Visible rows of each textarea. */
    rows?: number;
};

/** Editor of a list of texts (paragraphs, bullet points). */
export function StringListEditor({ rows = 2, lang, ...list }: StringListProps) {
    const { name, items, onChange, errors, itemLabel } = list;

    return (
        <ListFrame {...list} blank="">
            {(item, index, fresh) => (
                <>
                    <Textarea
                        value={item}
                        rows={rows}
                        lang={lang}
                        autoFocus={fresh}
                        aria-label={`${itemLabel} ${index + 1}`}
                        aria-invalid={
                            errors[`${name}.${index}`] ? true : undefined
                        }
                        onChange={(event) =>
                            onChange(
                                replaceAt(items, index, event.target.value),
                            )
                        }
                    />
                    <InputError message={errors[`${name}.${index}`]} />
                </>
            )}
        </ListFrame>
    );
}

type PairListProps<A extends string, B extends string> = ListProps<
    Record<A | B, string>
> & {
    /** The short, one-line part of an entry (title, question). */
    first: { key: A; label: string };
    /** The long part of an entry (text, answer). */
    second: { key: B; label: string; rows?: number };
};

/** Editor of a list of two-part entries: {title, text} or {q, a}. */
export function PairListEditor<A extends string, B extends string>({
    first,
    second,
    lang,
    ...list
}: PairListProps<A, B>) {
    const { name, items, onChange, errors } = list;
    const id = useId();

    const blank = { [first.key]: '', [second.key]: '' } as Record<
        A | B,
        string
    >;

    const update = (index: number, key: A | B, text: string): void => {
        onChange(replaceAt(items, index, { ...items[index], [key]: text }));
    };

    return (
        <ListFrame {...list} blank={blank}>
            {(item, index, fresh) => {
                const firstError = errors[`${name}.${index}.${first.key}`];
                const secondError = errors[`${name}.${index}.${second.key}`];

                return (
                    <>
                        <div className="grid grid-cols-1 gap-1.5">
                            <Label
                                htmlFor={`${id}-${index}-a`}
                                className="text-xs text-muted-foreground"
                            >
                                {first.label}
                            </Label>
                            <Input
                                id={`${id}-${index}-a`}
                                value={item[first.key]}
                                lang={lang}
                                autoFocus={fresh}
                                aria-invalid={firstError ? true : undefined}
                                onChange={(event) =>
                                    update(index, first.key, event.target.value)
                                }
                            />
                            <InputError message={firstError} />
                        </div>
                        <div className="grid grid-cols-1 gap-1.5">
                            <Label
                                htmlFor={`${id}-${index}-b`}
                                className="text-xs text-muted-foreground"
                            >
                                {second.label}
                            </Label>
                            <Textarea
                                id={`${id}-${index}-b`}
                                value={item[second.key]}
                                rows={second.rows ?? 3}
                                lang={lang}
                                aria-invalid={secondError ? true : undefined}
                                onChange={(event) =>
                                    update(
                                        index,
                                        second.key,
                                        event.target.value,
                                    )
                                }
                            />
                            <InputError message={secondError} />
                        </div>
                    </>
                );
            }}
        </ListFrame>
    );
}
