import { Head, router, useForm, usePage } from '@inertiajs/react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { City, Country } from 'country-state-city';
import InputError from '@/components/input-error';
import LogoUploader from '@/components/logo-uploader';
import { Badge } from '@/components/ui/badge';
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 { Spinner } from '@/components/ui/spinner';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type PartnerData = {
    name?: string | null;
    type?: 'e_commercant' | 'partenaire' | 'service_livraison' | null;
    product_types?: string[] | null;
    description?: string | null;
    phone?: string | null;
    country?: string | null;
    city?: string | null;
    address?: string | null;
    logo_url?: string | null;
    opening_hours?: {
        weekdays?: string | null;
        weekend?: string | null;
    } | null;
    social_links?: {
        website?: string | null;
        facebook?: string | null;
        instagram?: string | null;
        whatsapp?: string | null;
    } | null;
};

type Props = {
    partner?: PartnerData | null;
};

const PRODUCT_TYPES = [
    'Accessoires pour ordinateurs',
    'Beauté & cosmétique',
    'Bijoux',
    'Électronique',
    'Électroménager',
    'Épicerie',
    'Maison & décoration',
    'Mode & accessoires',
    'Produits de jardinage',
    'Santé & bien-être',
    'Services',
    'Sport & loisirs',
    'Téléphonie',
    'Transport & mobilité',
];

export default function PartnerSettings({ partner }: Props) {
    const allCountries = useMemo(() => Country.getAllCountries(), []);
    const [countryCode, setCountryCode] = useState(() => {
        if (!partner?.country) {
            return '';
        }
        const match = allCountries.find(
            (item) => item.name === partner.country,
        );
        return match?.isoCode ?? '';
    });

    const [shopRole, setShopRole] = useState(() => {
        const rawType = (partner?.type ?? '') as string;
        if (
            rawType === 'prestataire' ||
            rawType === 'service_livraison' ||
            rawType === 'partenaire'
        ) {
            return 'partenaire';
        }
        return partner?.type ?? 'e_commercant';
    });
    const [shopName, setShopName] = useState(partner?.name ?? '');
    const [description, setDescription] = useState(partner?.description ?? '');
    const [city, setCity] = useState(partner?.city ?? '');
    const [address, setAddress] = useState(partner?.address ?? '');
    const [phone, setPhone] = useState(partner?.phone ?? '');
    const [hoursWeekdays, setHoursWeekdays] = useState(
        partner?.opening_hours?.weekdays ?? '',
    );
    const [hoursWeekend, setHoursWeekend] = useState(
        partner?.opening_hours?.weekend ?? '',
    );
    const [website, setWebsite] = useState(
        partner?.social_links?.website ?? '',
    );
    const [facebook, setFacebook] = useState(
        partner?.social_links?.facebook ?? '',
    );
    const [instagram, setInstagram] = useState(
        partner?.social_links?.instagram ?? '',
    );
    const [whatsapp, setWhatsapp] = useState(
        partner?.social_links?.whatsapp ?? '',
    );
    const [typesOpen, setTypesOpen] = useState(false);
    const [typeQuery, setTypeQuery] = useState('');
    const [aiLoading, setAiLoading] = useState(false);
    const [aiError, setAiError] = useState('');
    const entityLabel = shopRole === 'partenaire' ? 'entreprise' : 'boutique';
    const entityLabelTitle = entityLabel === 'entreprise' ? 'Entreprise' : 'Boutique';

    const [selectedTypes, setSelectedTypes] = useState<string[]>(
        partner?.product_types ?? [],
    );
    const { data: formData, setData: setFormData } = useForm({
        logo: null as File | null,
    });
    const [submitting, setSubmitting] = useState(false);
    const logoInputRef = useRef<HTMLInputElement>(null);
    const countryName = useMemo(() => {
        const match = allCountries.find(
            (item) => item.isoCode === countryCode,
        );
        return match?.name ?? '';
    }, [allCountries, countryCode]);

    const cityOptions = useMemo(() => {
        if (!countryCode) {
            return [];
        }
        return City.getCitiesOfCountry(countryCode)
            .map((item) => item.name)
            .sort((a, b) => a.localeCompare(b, 'fr'));
    }, [countryCode]);

    const filteredTypes = useMemo(() => {
        const query = typeQuery.trim().toLowerCase();
        if (!query) {
            return PRODUCT_TYPES;
        }
        return PRODUCT_TYPES.filter((type) =>
            type.toLowerCase().includes(query),
        );
    }, [typeQuery]);

    useEffect(() => {
        if (city && !cityOptions.includes(city)) {
            setCity('');
        }
    }, [city, cityOptions]);

    const toggleType = (type: string) => {
        setSelectedTypes((prev) =>
            prev.includes(type)
                ? prev.filter((item) => item !== type)
                : [...prev, type],
        );
    };

    const removeType = (type: string) => {
        setSelectedTypes((prev) => prev.filter((item) => item !== type));
    };

    const getCsrfToken = () => {
        const cookie = document.cookie
            .split('; ')
            .find((row) => row.startsWith('XSRF-TOKEN='));
        if (!cookie) {
            return '';
        }
        return decodeURIComponent(cookie.split('=')[1] ?? '');
    };

    const handleGenerateDescription = async () => {
        setAiError('');
        setAiLoading(true);
        try {
            const response = await fetch('/create-shop/ai-description', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                    'X-XSRF-TOKEN': getCsrfToken(),
                },
                body: JSON.stringify({
                    name: shopName,
                    type: shopRole,
                    product_types: selectedTypes,
                    country: countryName,
                    city,
                }),
            });

            if (!response.ok) {
                const payload = await response.json().catch(() => null);
                throw new Error(
                    payload?.message ??
                        "Impossible de générer la description.",
                );
            }

            const payload = await response.json();
            setDescription(payload.description ?? '');
        } catch (error) {
            setAiError(
                error instanceof Error
                    ? error.message
                    : "Impossible de générer la description.",
            );
        } finally {
            setAiLoading(false);
        }
    };

    const breadcrumbs: BreadcrumbItem[] = [
        { title: `Paramètres de ${entityLabel}`, href: '/parametres-boutique' },
    ];

    const page = usePage().props as { errors?: Record<string, string> };
    const pageErrors = page.errors ?? {};

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setSubmitting(true);
        const payload = {
            name: shopName,
            type: shopRole,
            country: countryName,
            city,
            address,
            phone,
            description,
            product_types: selectedTypes,
            logo: formData.logo,
            opening_hours_weekdays: hoursWeekdays,
            opening_hours_weekend: hoursWeekend,
            social_website: website,
            social_facebook: facebook,
            social_instagram: instagram,
            social_whatsapp: whatsapp,
        };
        router.post('/parametres-boutique', payload, {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => router.reload({ preserveScroll: true }),
            onStart: () => setSubmitting(true),
            onFinish: () => setSubmitting(false),
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Paramètres de ${entityLabel}`} />

            <form
                action="/parametres-boutique"
                method="post"
                encType="multipart/form-data"
                className="space-y-6 p-4"
                onSubmit={handleSubmit}
            >
                        <Card>
                            <CardHeader>
                                <CardTitle>Identité visuelle</CardTitle>
                                <p className="text-sm font-normal text-muted-foreground mt-1">
                                    Vous pouvez changer le logo de la {entityLabel} en sélectionnant une nouvelle image ci-dessous, puis en cliquant sur « Enregistrer les changements ».
                                </p>
                            </CardHeader>
                            <CardContent className="grid gap-4">
                                <LogoUploader
                                    label={`Logo de la ${entityLabel}`}
                                    currentUrl={partner?.logo_url ?? null}
                                    error={pageErrors.logo}
                                    inputRef={logoInputRef}
                                    onFileChange={(file) => setFormData('logo', file)}
                                />
                                <Button type="submit" disabled={submitting}>
                                    {submitting && <Spinner />}
                                    Enregistrer les changements
                                </Button>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Informations principales</CardTitle>
                            </CardHeader>
                            <CardContent className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2 md:col-span-2">
                                    <Label>Nom de la {entityLabel}</Label>
                                    <Input
                                        name="name"
                                        value={shopName}
                                        onChange={(event) =>
                                            setShopName(event.target.value)
                                        }
                                    />
                                    <InputError message={pageErrors.name} />
                                </div>

                                <div className="space-y-2">
                                    <Label>Rôle de l&apos;{entityLabel}</Label>
                                    <Select
                                        value={shopRole}
                                        onValueChange={setShopRole}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Choisir un rôle" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="e_commercant">
                                                Vendre les produits
                                            </SelectItem>
                                            <SelectItem value="partenaire">
                                                Vendre ou mettre en avant mes services
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <InputError message={pageErrors.type} />
                                </div>

                                <div className="space-y-2 md:col-span-2">
                                    <Label>Types de produits</Label>
                                    <button
                                        type="button"
                                        className="flex min-h-[44px] w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm text-muted-foreground"
                                        onClick={() =>
                                            setTypesOpen((open) => !open)
                                        }
                                    >
                                        <span>
                                            {selectedTypes.length > 0
                                                ? `Cliquez pour sélectionner (${selectedTypes.length} sélectionné(s))`
                                                : 'Cliquez pour sélectionner'}
                                        </span>
                                        <span className="text-xs">▾</span>
                                    </button>

                                    {selectedTypes.length > 0 && (
                                        <div className="flex flex-wrap gap-2">
                                            {selectedTypes.map((type) => (
                                                <Badge
                                                    key={type}
                                                    variant="secondary"
                                                    className="gap-2"
                                                >
                                                    {type}
                                                    <button
                                                        type="button"
                                                        className="text-xs"
                                                        onClick={() => removeType(type)}
                                                    >
                                                        ✕
                                                    </button>
                                                </Badge>
                                            ))}
                                        </div>
                                    )}

                                    {typesOpen && (
                                        <div className="grid gap-2 rounded-md border border-input bg-background p-3">
                                            <Input
                                                value={typeQuery}
                                                onChange={(event) =>
                                                    setTypeQuery(event.target.value)
                                                }
                                                placeholder="Rechercher un type de produit"
                                            />
                                            {filteredTypes.length === 0 ? (
                                                <p className="text-xs text-muted-foreground">
                                                    Aucun type ne correspond.
                                                </p>
                                            ) : null}
                                            {filteredTypes.map((type) => {
                                                const checked =
                                                    selectedTypes.includes(type);
                                                return (
                                                    <label
                                                        key={type}
                                                        className="flex items-center gap-3 text-sm"
                                                    >
                                                        <input
                                                            type="checkbox"
                                                            value={type}
                                                            checked={checked}
                                                            onChange={() =>
                                                                toggleType(type)
                                                            }
                                                            className="h-4 w-4 rounded border-input"
                                                        />
                                                        {type}
                                                    </label>
                                                );
                                            })}
                                        </div>
                                    )}
                                    <InputError message={pageErrors.product_types} />
                                </div>

                                <div className="space-y-2 md:col-span-2">
                                    <div className="flex items-center justify-between">
                                        <Label>Description</Label>
                                        <Button
                                            type="button"
                                            variant="link"
                                            size="sm"
                                            disabled={aiLoading}
                                            onClick={handleGenerateDescription}
                                        >
                                            {aiLoading
                                                ? 'Génération...'
                                                : "Générer la description avec l'IA"}
                                        </Button>
                                    </div>
                                    {aiError ? (
                                        <p className="text-xs text-red-600">
                                            {aiError}
                                        </p>
                                    ) : null}
                                    <textarea
                                        name="description"
                                        rows={4}
                                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                                        placeholder={`Décrivez votre ${entityLabel}`}
                                        value={description}
                                        onChange={(event) =>
                                            setDescription(event.target.value)
                                        }
                                    />
                                    <InputError message={pageErrors.description} />
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Contact et localisation</CardTitle>
                            </CardHeader>
                            <CardContent className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2">
                                    <Label>Téléphone</Label>
                                    <Input
                                        name="phone"
                                        value={phone}
                                        onChange={(event) =>
                                            setPhone(event.target.value)
                                        }
                                    />
                                    <InputError message={pageErrors.phone} />
                                </div>
                                <div className="space-y-2">
                                    <Label>Pays</Label>
                                    <Select
                                        value={countryCode}
                                        onValueChange={(value) => {
                                            setCountryCode(value);
                                        }}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Sélectionner un pays" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {allCountries.map((item) => (
                                                <SelectItem
                                                    key={item.isoCode}
                                                    value={item.isoCode}
                                                >
                                                    {item.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <InputError message={pageErrors.country} />
                                </div>
                                <div className="space-y-2">
                                    <Label>Ville</Label>
                                    <Select
                                        value={city}
                                        onValueChange={setCity}
                                        disabled={!countryCode}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Sélectionner une ville" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {cityOptions.map((item) => (
                                                <SelectItem key={item} value={item}>
                                                    {item}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <InputError message={pageErrors.city} />
                                </div>
                                <div className="space-y-2 md:col-span-2">
                                    <Label>Adresse</Label>
                                    <Input
                                        name="address"
                                        value={address}
                                        onChange={(event) =>
                                            setAddress(event.target.value)
                                        }
                                    />
                                    <InputError message={pageErrors.address} />
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Horaires</CardTitle>
                            </CardHeader>
                            <CardContent className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2">
                                    <Label>Semaine</Label>
                                    <Input
                                        name="opening_hours_weekdays"
                                        value={hoursWeekdays}
                                        onChange={(event) =>
                                            setHoursWeekdays(event.target.value)
                                        }
                                        placeholder="Lun - Ven: 08:00 - 18:00"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Weekend</Label>
                                    <Input
                                        name="opening_hours_weekend"
                                        value={hoursWeekend}
                                        onChange={(event) =>
                                            setHoursWeekend(event.target.value)
                                        }
                                        placeholder="Sam - Dim: 10:00 - 16:00"
                                    />
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Réseaux sociaux</CardTitle>
                            </CardHeader>
                            <CardContent className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2">
                                    <Label>Site web</Label>
                                    <Input
                                        name="social_website"
                                        value={website}
                                        onChange={(event) =>
                                            setWebsite(event.target.value)
                                        }
                                        placeholder="https://"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Facebook</Label>
                                    <Input
                                        name="social_facebook"
                                        value={facebook}
                                        onChange={(event) =>
                                            setFacebook(event.target.value)
                                        }
                                        placeholder="@votrepage"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Instagram</Label>
                                    <Input
                                        name="social_instagram"
                                        value={instagram}
                                        onChange={(event) =>
                                            setInstagram(event.target.value)
                                        }
                                        placeholder="@votrecompte"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>WhatsApp</Label>
                                    <Input
                                        name="social_whatsapp"
                                        value={whatsapp}
                                        onChange={(event) =>
                                            setWhatsapp(event.target.value)
                                        }
                                        placeholder="+237 6XX XX XX XX"
                                    />
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Collaborations</CardTitle>
                            </CardHeader>
                            <CardContent className="flex flex-col gap-2 text-sm">
                                <p className="text-muted-foreground">
                                    Connectez votre {entityLabel} à des services de
                                    livraison pour automatiser vos expéditions.
                                </p>
                                <Button variant="outline" asChild className="w-fit">
                                    <a href="/services-livraison">
                                        Gérer les services de livraison
                                    </a>
                                </Button>
                            </CardContent>
                        </Card>

                        <div>
                            <Button type="submit" disabled={submitting}>
                                {submitting && <Spinner />}
                                Enregistrer les changements
                            </Button>
                        </div>
            </form>
        </AppLayout>
    );
}
