import { ImageUp, Trash2, Undo2 } from 'lucide-react';
import { useRef } from 'react';
import type { ReactNode } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';

/** Upload limit enforced by the server (SiteSettingsUpdateRequest). */
const MAX_BYTES = 1024 * 1024;

type Props = {
    id: string;
    label: string;
    /** Public path of the image that is stored now, if any. */
    current: string | null;
    /** A newly chosen file that replaces the stored image on save. */
    file: File | null;
    /** Whether the stored image is deleted on save. */
    removed: boolean;
    onSelect: (file: File | null) => void;
    onRemove: (removed: boolean) => void;
    error?: string;
    hint?: ReactNode;
    /** Show the image on a dark tile (logos drawn for dark backgrounds). */
    dark?: boolean;
    /** What the site uses while nothing is stored: shown faded in the tile. */
    fallback?: string | null;
};

/**
 * An image setting: shows the stored image and lets the editor replace or
 * remove it. Nothing is uploaded or deleted until the form is saved.
 */
export function ImageField({
    id,
    label,
    current,
    file,
    removed,
    onSelect,
    onRemove,
    error,
    hint,
    dark = false,
    fallback = null,
}: Props) {
    const input = useRef<HTMLInputElement>(null);
    const shown = removed ? null : current;
    const tooLarge = file !== null && file.size > MAX_BYTES;

    return (
        <div className="grid grid-cols-1 content-start gap-2">
            <Label htmlFor={id} className="leading-normal">
                {label}
            </Label>

            <div className="flex flex-wrap items-center gap-4">
                <div
                    className={cn(
                        'flex h-20 w-40 shrink-0 items-center justify-center overflow-hidden rounded-md border p-2',
                        dark ? 'bg-neutral-900' : 'bg-white',
                    )}
                >
                    {shown ? (
                        <img
                            src={shown}
                            alt={`Yüklü ${label.toLocaleLowerCase('tr')}`}
                            className="max-h-full max-w-full object-contain"
                        />
                    ) : fallback ? (
                        <img
                            src={fallback}
                            alt="Varsayılan görsel"
                            className="max-h-full max-w-full object-contain opacity-50"
                        />
                    ) : (
                        <span
                            className={cn(
                                'text-xs',
                                dark ? 'text-neutral-400' : 'text-neutral-500',
                            )}
                        >
                            Görsel yok
                        </span>
                    )}
                </div>

                <div className="grid grid-cols-1 gap-2">
                    <div className="flex flex-wrap gap-2">
                        {/* The button is the control; the native input stays hidden. */}
                        <Button
                            id={id}
                            type="button"
                            variant="outline"
                            size="sm"
                            aria-describedby={hint ? `${id}-hint` : undefined}
                            onClick={() => input.current?.click()}
                        >
                            <ImageUp />
                            {current ? 'Değiştir' : 'Dosya seç'}
                        </Button>
                        <input
                            ref={input}
                            type="file"
                            accept=".svg,.png,.webp,.jpg,.jpeg"
                            className="hidden"
                            tabIndex={-1}
                            aria-hidden="true"
                            onChange={(event) => {
                                const chosen = event.target.files?.[0] ?? null;

                                // Lets the same file be chosen again later.
                                event.target.value = '';
                                onSelect(chosen);
                            }}
                        />

                        {current && !removed && file === null && (
                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() => onRemove(true)}
                            >
                                <Trash2 />
                                Kaldır
                            </Button>
                        )}

                        {(removed || file !== null) && (
                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() => {
                                    onSelect(null);
                                    onRemove(false);
                                }}
                            >
                                <Undo2 />
                                Geri al
                            </Button>
                        )}
                    </div>

                    {file !== null && (
                        <p className="text-xs text-muted-foreground">
                            Seçilen dosya:{' '}
                            <span className="font-medium text-foreground">
                                {file.name}
                            </span>{' '}
                            ({Math.max(1, Math.round(file.size / 1024))} KB) —
                            kaydedince yüklenir.
                        </p>
                    )}

                    {removed && file === null && (
                        <p className="text-xs text-muted-foreground">
                            Görsel kaydedince kaldırılır.
                        </p>
                    )}
                </div>
            </div>

            {hint && (
                <p id={`${id}-hint`} className="text-xs text-muted-foreground">
                    {hint}
                </p>
            )}

            <InputError
                message={
                    error ??
                    (tooLarge
                        ? 'Dosya 1 MB’tan büyük; daha küçük bir dosya seçin.'
                        : undefined)
                }
            />
        </div>
    );
}
