import { Link, router } from '@inertiajs/react';
import { ChevronLeft, Plus } from 'lucide-react';
import { useState } from 'react';
import { PageHeader } from '@/components/shared/page-header';
import { SectionCard } from '@/components/shared/section-card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { index as leadCaptureIndex } from '@/routes/catalog/lead-capture';
import type { LeadCaptureBrandShowProps } from '@/types/catalog';

export function LeadCaptureBrandView({
    brand,
    models,
}: LeadCaptureBrandShowProps) {
    const [editing, setEditing] = useState<number | null>(null);
    const [showCreate, setShowCreate] = useState(false);

    const toggle = (id: number) =>
        router.post(
            `/lead-capture/models/${id}/toggle`,
            {},
            { preserveScroll: true },
        );

    const destroy = (id: number, name: string) => {
        if (window.confirm(`Delete model "${name}"?`)) {
            router.delete(`/lead-capture/models/${id}`, {
                preserveScroll: true,
            });
        }
    };

    return (
        <div className="custom-scroll flex-1 overflow-y-auto">
            <PageHeader title={brand.name} subtitle="Lead Capture — models">
                <Link
                    href={leadCaptureIndex()}
                    prefetch="hover"
                    className="inline-flex cursor-pointer items-center gap-1 text-[10px] font-bold tracking-widest text-gray-400 uppercase transition-colors hover:text-astara-orange"
                >
                    <ChevronLeft size={12} /> Back to Lead Capture
                </Link>
            </PageHeader>

            <div className="p-5">
                <SectionCard
                    title="Models"
                    titleRight={
                        <span className="text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                            {models.length}
                        </span>
                    }
                >
                    <div className="border-b border-gray-50 px-4 py-2">
                        {!showCreate ? (
                            <Button
                                type="button"
                                size="sm"
                                variant="outline"
                                onClick={() => setShowCreate(true)}
                            >
                                <Plus size={14} /> New model
                            </Button>
                        ) : (
                            <CreateModelForm
                                brand={brand}
                                onClose={() => setShowCreate(false)}
                            />
                        )}
                    </div>
                    <div className="divide-y divide-gray-50">
                        {models.map((model) => (
                            <div
                                key={model.id}
                                className="flex items-center gap-3 px-4 py-3"
                            >
                                <img
                                    src={model.image_url ?? undefined}
                                    alt={model.name}
                                    className="h-9 w-14 shrink-0 rounded object-cover"
                                    onError={(e) => {
                                        (
                                            e.currentTarget as HTMLImageElement
                                        ).style.display = 'none';
                                    }}
                                />
                                <div className="min-w-0 flex-1">
                                    {editing === model.id ? (
                                        <EditModelForm
                                            model={model}
                                            onDone={() => setEditing(null)}
                                        />
                                    ) : (
                                        <div>
                                            <p className="truncate text-[11px] font-bold text-astara-purple">
                                                {model.name}
                                            </p>
                                            <p className="font-mono text-[10px] text-gray-400">
                                                {model.code} · familia:{' '}
                                                {model.familia_id ?? '—'}
                                            </p>
                                        </div>
                                    )}
                                </div>
                                {editing !== model.id && (
                                    <button
                                        type="button"
                                        onClick={() => setEditing(model.id)}
                                        className="cursor-pointer text-[10px] font-bold text-astara-purple transition-colors hover:text-astara-orange"
                                    >
                                        Edit
                                    </button>
                                )}
                                <button
                                    type="button"
                                    onClick={() => toggle(model.id)}
                                    className={cn(
                                        'inline-flex h-[16px] cursor-pointer items-center rounded px-1.5 text-[8px] font-bold tracking-wider uppercase transition-colors',
                                        model.active
                                            ? 'bg-green-50 text-green-700'
                                            : 'bg-gray-100 text-gray-400',
                                    )}
                                >
                                    {model.active ? 'on' : 'off'}
                                </button>
                                {editing !== model.id && (
                                    <button
                                        type="button"
                                        onClick={() =>
                                            destroy(model.id, model.name)
                                        }
                                        className="cursor-pointer text-[10px] font-bold text-gray-300 transition-colors hover:text-red-600"
                                    >
                                        Delete
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>
                </SectionCard>
            </div>
        </div>
    );
}

function EditModelForm({
    model,
    onDone,
}: {
    model: LeadCaptureBrandShowProps['models'][number];
    onDone: () => void;
}) {
    const [name, setName] = useState(model.name);
    const [familiaId, setFamiliaId] = useState(model.familia_id ?? '');
    const [imageUrl, setImageUrl] = useState(model.image_url ?? '');

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        router.patch(
            `/lead-capture/models/${model.id}`,
            {
                name,
                familia_id: familiaId || null,
                image_url: imageUrl || null,
                brochure_pdf: model.brochure_pdf,
                price_list_pdf: model.price_list_pdf,
            },
            { preserveScroll: true, onSuccess: onDone },
        );
    };

    return (
        <form onSubmit={submit} className="flex flex-wrap items-end gap-2">
            <div>
                <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                    Name
                </label>
                <Input
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required
                    className="h-8 w-40 bg-white text-xs"
                />
            </div>
            <div>
                <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                    Familia ID
                </label>
                <Input
                    value={familiaId}
                    onChange={(e) => setFamiliaId(e.target.value)}
                    className="h-8 w-48 bg-white font-mono text-xs"
                />
            </div>
            <div>
                <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                    Image URL
                </label>
                <Input
                    value={imageUrl}
                    onChange={(e) => setImageUrl(e.target.value)}
                    className="h-8 w-64 bg-white font-mono text-xs"
                />
            </div>
            <div className="flex items-center gap-1.5">
                <Button type="submit" size="sm">
                    Save
                </Button>
                <Button
                    type="button"
                    size="sm"
                    variant="ghost"
                    onClick={onDone}
                >
                    Cancel
                </Button>
            </div>
        </form>
    );
}

function CreateModelForm({
    brand,
    onClose,
}: {
    brand: LeadCaptureBrandShowProps['brand'];
    onClose: () => void;
}) {
    const [code, setCode] = useState('');
    const [name, setName] = useState('');
    const [familiaId, setFamiliaId] = useState('');

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        router.post(
            `/lead-capture/brands/${brand.code}/models`,
            { code, name, familia_id: familiaId || null },
            { preserveScroll: true, onSuccess: onClose },
        );
    };

    return (
        <form onSubmit={submit} className="flex flex-wrap items-end gap-2">
            <div>
                <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                    Code
                </label>
                <Input
                    value={code}
                    onChange={(e) => setCode(e.target.value)}
                    required
                    className="h-8 w-40 bg-white font-mono text-xs"
                    placeholder="hyundai_i30"
                />
            </div>
            <div>
                <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                    Name
                </label>
                <Input
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required
                    className="h-8 w-40 bg-white text-xs"
                    placeholder="i30"
                />
            </div>
            <div>
                <label className="mb-1 block text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                    Familia ID
                </label>
                <Input
                    value={familiaId}
                    onChange={(e) => setFamiliaId(e.target.value)}
                    className="h-8 w-48 bg-white font-mono text-xs"
                />
            </div>
            <div className="flex items-center gap-1.5">
                <Button type="submit" size="sm">
                    Create
                </Button>
                <Button
                    type="button"
                    size="sm"
                    variant="ghost"
                    onClick={onClose}
                >
                    Cancel
                </Button>
            </div>
        </form>
    );
}
