import { Form, Head, Link } from '@inertiajs/react';
import { ArrowLeft } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { FileUploadMultiple } from '@/components/inputs';
import { InputError } from '@/components/ui';
import { NumberInput } from '@/components/inputs';
import { RupiahInput } from '@/components/inputs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { index as productIndex } from '@/routes/admin/master/products';

type Props = {
    variant: {
        id: number;
        product_id: number;
        name: string;
        stock: number;
        reject_stock: number;
        retail_stock: number;
        photo_keys: string[];
        photo_urls: string[];
        prices: Array<{ type: string; price: number }>;
    };
};

const PRICE_TYPES = [
    { key: 'distributor', label: 'Distributor' },
    { key: 'agent', label: 'Agen' },
    { key: 'sub_agent', label: 'Sub Agen' },
    { key: 'wholesale', label: 'Grosir' },
    { key: 'retail', label: 'Ecer' },
    { key: 'tiktok', label: 'TikTok' },
    { key: 'shopee', label: 'Shopee' },
    { key: 'capital', label: 'Modal' },
    { key: 'reject', label: 'Reject' },
];

export default function ProductVariantEdit({ variant }: Props) {
    const [name, setName] = useState(variant.name);
    const [stock, setStock] = useState(variant.stock);
    const [rejectStock, setRejectStock] = useState(variant.reject_stock);
    const [retailStock, setRetailStock] = useState(variant.retail_stock);
    const [photos, setPhotos] = useState<Array<{ key: string; url: string | null }>>(
        variant.photo_keys.map((key, i) => ({
            key,
            url: variant.photo_urls[i] ?? null,
        })),
    );
    const [uploading, setUploading] = useState(false);
    const [prices, setPrices] = useState<
        Array<{ type: string; price: number }>
    >(
        variant.prices.length > 0
            ? variant.prices
            : PRICE_TYPES.map((pt) => ({ type: pt.key, price: 0 })),
    );

    function updatePrice(priceIndex: number, value: number) {
        setPrices((prev) =>
            prev.map((p, i) => (i === priceIndex ? { ...p, price: value } : p)),
        );
    }

    function getPayload() {
        return {
            name,
            stock: Number(stock),
            reject_stock: Number(rejectStock),
            retail_stock: Number(retailStock),
            photo_keys: photos.map((p) => p.key),
            prices: prices.map((p) => ({
                type: p.type,
                price: Number(p.price),
            })),
        };
    }

    return (
        <>
            <Head title="Edit Varian" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <h2 className="text-2xl font-semibold tracking-tight">
                        Edit Varian
                    </h2>
                    <Button asChild variant="outline">
                        <Link href={productIndex.url()}>
                            <ArrowLeft className="h-4 w-4" />
                            Kembali
                        </Link>
                    </Button>
                </div>

                <Form
                    action={`/admin/master/products/${variant.product_id}/variants/${variant.id}`}
                    method="put"
                    transform={() => getPayload()}
                    onError={() => {
                        toast.error('Ada data yang belum sesuai, silakan periksa kembali input Anda.');
                    }}
                >
                    {({ errors, processing }) => (
                        <>
                            <div className="grid gap-6">
                                <Card>
                                    <CardHeader>
                                        <CardTitle>Informasi Varian</CardTitle>
                                    </CardHeader>
                                    <CardContent className="grid grid-cols-1 gap-4 md:grid-cols-4">
                                        <div className="grid gap-2">
                                            <Label>
                                                Nama Varian{' '}
                                                <span className="text-destructive">
                                                    *
                                                </span>
                                            </Label>
                                            <Input
                                                value={name}
                                                onChange={(e) =>
                                                    setName(e.target.value)
                                                }
                                                placeholder="Contoh: Ukuran L, Warna Merah"
                                            />
                                            <InputError message={errors.name} />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label>
                                                Stok Bagus{' '}
                                                <span className="text-destructive">
                                                    *
                                                </span>
                                            </Label>
                                            <NumberInput
                                                value={stock}
                                                onValueChange={setStock}
                                            />
                                            <InputError
                                                message={errors.stock}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label>
                                                Stok Reject{' '}
                                                <span className="text-destructive">
                                                    *
                                                </span>
                                            </Label>
                                            <NumberInput
                                                value={rejectStock}
                                                onValueChange={setRejectStock}
                                            />
                                            <InputError
                                                message={errors.reject_stock}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label>
                                                Stok Ecer{' '}
                                                <span className="text-destructive">
                                                    *
                                                </span>
                                            </Label>
                                            <NumberInput
                                                value={retailStock}
                                                onValueChange={setRetailStock}
                                            />
                                            <InputError
                                                message={errors.retail_stock}
                                            />
                                        </div>
                                    </CardContent>
                                </Card>

                                <Card>
                                    <CardHeader>
                                        <CardTitle>Foto Varian</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <FileUploadMultiple
                                            value={photos}
                                            onChange={setPhotos}
                                            folder="product-variant"
                                            maxItems={5}
                                            onUploadingChange={setUploading}
                                        />
                                        <InputError
                                            message={errors.photo_keys}
                                        />
                                    </CardContent>
                                </Card>

                                <Card>
                                    <CardHeader>
                                        <CardTitle>Harga</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
                                            {PRICE_TYPES.map(
                                                (priceType, priceIndex) => (
                                                    <div
                                                        key={priceType.key}
                                                        className="grid gap-2"
                                                    >
                                                        <Label>
                                                            Harga{' '}
                                                            {priceType.label}{' '}
                                                            <span className="text-destructive">
                                                                *
                                                            </span>
                                                        </Label>
                                                        <RupiahInput
                                                            value={
                                                                prices[
                                                                    priceIndex
                                                                ]?.price ?? 0
                                                            }
                                                            onValueChange={(
                                                                val,
                                                            ) =>
                                                                updatePrice(
                                                                    priceIndex,
                                                                    val,
                                                                )
                                                            }
                                                        />
                                                        <InputError
                                                            message={
                                                                errors[
                                                                    `prices.${priceIndex}.price`
                                                                ]
                                                            }
                                                        />
                                                    </div>
                                                ),
                                            )}
                                        </div>
                                    </CardContent>
                                </Card>
                            </div>

                            <div className="mt-6 flex items-center gap-4">
                                <Button
                                    type="submit"
                                    disabled={processing || uploading}
                                >
                                    {processing
                                        ? 'Menyimpan...'
                                        : uploading
                                          ? 'Mengunggah...'
                                          : 'Simpan'}
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}
