import { Form, Head, Link } from '@inertiajs/react';
import type { ChangeEvent } from 'react';
import { useState } from 'react';
import TransferRouteController from '@/actions/App/Http/Controllers/Admin/TransferRouteController';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import { dashboard } from '@/routes/admin';
import { index } from '@/routes/admin/routes';

type EditableRoute = {
    id: number;
    origin: string;
    destination: string;
    duration_minutes: number;
    distance_km: string;
    price: number;
    image: string | null;
    is_popular: boolean;
    is_high_demand: boolean;
    is_active: boolean;
    sort_order: number;
};

function Toggle({
    name,
    label,
    description,
    defaultChecked,
}: {
    name: string;
    label: string;
    description: string;
    defaultChecked: boolean;
}) {
    return (
        <label className="flex cursor-pointer items-start gap-3 rounded-lg border p-4">
            <input type="hidden" name={name} value="0" />
            <input
                type="checkbox"
                name={name}
                value="1"
                defaultChecked={defaultChecked}
                className="mt-0.5 size-4 accent-[#d6a04a]"
            />
            <span>
                <span className="block text-sm font-medium">{label}</span>
                <span className="text-xs text-muted-foreground">
                    {description}
                </span>
            </span>
        </label>
    );
}

export default function RouteForm({ route }: { route: EditableRoute | null }) {
    const [preview, setPreview] = useState(route?.image ?? null);
    const action = route
        ? TransferRouteController.update.form(route.id)
        : TransferRouteController.store.form();

    const handleImage = (event: ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];

        setPreview(file ? URL.createObjectURL(file) : (route?.image ?? null));
    };

    return (
        <>
            <Head title={route ? 'Edit route' : 'Add route'} />
            <div className="max-w-3xl space-y-6 p-4 sm:p-6">
                <Heading
                    title={route ? 'Edit route' : 'Add route'}
                    description="This route will appear as a card on the home page"
                />

                <Card>
                    <CardContent className="pt-6">
                        <Form
                            {...action}
                            encType="multipart/form-data"
                            className="space-y-6"
                        >
                            {({ processing, errors }) => (
                                <>
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <div className="grid gap-2">
                                            <Label htmlFor="origin">From</Label>
                                            <Input
                                                id="origin"
                                                name="origin"
                                                defaultValue={route?.origin}
                                                placeholder="Naples"
                                                required
                                            />
                                            <InputError
                                                message={errors.origin}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="destination">
                                                To
                                            </Label>
                                            <Input
                                                id="destination"
                                                name="destination"
                                                defaultValue={
                                                    route?.destination
                                                }
                                                placeholder="Positano"
                                                required
                                            />
                                            <InputError
                                                message={errors.destination}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="duration_minutes">
                                                Duration (minutes)
                                            </Label>
                                            <Input
                                                id="duration_minutes"
                                                name="duration_minutes"
                                                type="number"
                                                min={1}
                                                defaultValue={
                                                    route?.duration_minutes
                                                }
                                                required
                                            />
                                            <InputError
                                                message={
                                                    errors.duration_minutes
                                                }
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="distance_km">
                                                Distance (km)
                                            </Label>
                                            <Input
                                                id="distance_km"
                                                name="distance_km"
                                                type="number"
                                                step="0.1"
                                                min={0.1}
                                                defaultValue={
                                                    route?.distance_km
                                                }
                                                required
                                            />
                                            <InputError
                                                message={errors.distance_km}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="price">
                                                Starting price (USD)
                                            </Label>
                                            <Input
                                                id="price"
                                                name="price"
                                                type="number"
                                                step="0.01"
                                                min={1}
                                                defaultValue={route?.price}
                                                required
                                            />
                                            <InputError
                                                message={errors.price}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="sort_order">
                                                Display order
                                            </Label>
                                            <Input
                                                id="sort_order"
                                                name="sort_order"
                                                type="number"
                                                min={0}
                                                defaultValue={
                                                    route?.sort_order ?? 0
                                                }
                                            />
                                            <InputError
                                                message={errors.sort_order}
                                            />
                                        </div>
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="image">Image</Label>
                                        {preview && (
                                            <img
                                                src={preview}
                                                alt=""
                                                className="aspect-[16/9] w-full max-w-sm rounded-lg object-cover"
                                            />
                                        )}
                                        <Input
                                            id="image"
                                            name="image"
                                            type="file"
                                            accept="image/jpeg,image/png,image/webp"
                                            onChange={handleImage}
                                        />
                                        <p className="text-xs text-muted-foreground">
                                            JPG, PNG or WebP, up to 4 MB.
                                            {route &&
                                                ' Leave empty to keep the current image.'}
                                        </p>
                                        <InputError message={errors.image} />
                                    </div>

                                    <div className="grid gap-3 sm:grid-cols-3">
                                        <Toggle
                                            name="is_popular"
                                            label="Most popular"
                                            description="Show in the popular routes slider"
                                            defaultChecked={
                                                route?.is_popular ?? true
                                            }
                                        />
                                        <Toggle
                                            name="is_high_demand"
                                            label="High demand"
                                            description="Show in High Demand Connections"
                                            defaultChecked={
                                                route?.is_high_demand ?? false
                                            }
                                        />
                                        <Toggle
                                            name="is_active"
                                            label="Visible"
                                            description="Uncheck to hide without deleting"
                                            defaultChecked={
                                                route?.is_active ?? true
                                            }
                                        />
                                    </div>

                                    <div className="flex gap-3">
                                        <Button disabled={processing}>
                                            {processing && <Spinner />}
                                            {route
                                                ? 'Save changes'
                                                : 'Create route'}
                                        </Button>
                                        <Button variant="ghost" asChild>
                                            <Link href={index()}>Cancel</Link>
                                        </Button>
                                    </div>
                                </>
                            )}
                        </Form>
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

RouteForm.layout = {
    breadcrumbs: [
        { title: 'Admin', href: dashboard() },
        { title: 'Routes', href: index() },
    ],
};
