import { Form, Head, router } from '@inertiajs/react';
import { AlertTriangle } from 'lucide-react';
import { useState } from 'react';
import CompanyController from '@/actions/App/Http/Controllers/Settings/CompanyController';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import companyRoutes, { edit } from '@/routes/company';
import type { Company } from '@/types';

type Props = {
    company: Company;
    hasFormatempPassword: boolean;
    formatempEnvironments: { value: string; label: string }[];
};

export default function CompanySettings({
    company,
    hasFormatempPassword,
    formatempEnvironments,
}: Props) {
    // Controlled so the collaudo warning follows the choice, not only the saved value.
    const [environment, setEnvironment] = useState(
        company.formatemp_environment ?? 'collaudo',
    );

    // The credentials belong to the ente: the check runs server side with the stored
    // password, which never travels back to the browser.
    function testFormatempConnection() {
        router.post(
            companyRoutes.formatemp.test().url,
            {},
            { preserveScroll: true },
        );
    }

    return (
        <>
            <Head title="Azienda e Forma.Temp" />

            <h1 className="sr-only">Azienda e Forma.Temp</h1>

            <div className="space-y-6">
                <Heading
                    variant="small"
                    title="Azienda e Forma.Temp"
                    description="Dati anagrafici, di fatturazione e credenziali per la sincronizzazione con Forma.Temp"
                />

                <Form
                    {...CompanyController.update.form()}
                    options={{
                        preserveScroll: true,
                    }}
                    className="space-y-8"
                >
                    {({ processing, errors, recentlySuccessful }) => (
                        <>
                            <section className="space-y-6">
                                <h3 className="text-sm font-medium">
                                    Dati azienda
                                </h3>

                                <div className="grid gap-2">
                                    <Label htmlFor="name">
                                        Ragione sociale
                                    </Label>
                                    <Input
                                        id="name"
                                        name="name"
                                        required
                                        defaultValue={company.name}
                                        placeholder="Nome ente / azienda"
                                    />
                                    <InputError message={errors.name} />
                                </div>

                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div className="grid gap-2">
                                        <Label htmlFor="vat_number">
                                            Partita IVA
                                        </Label>
                                        <Input
                                            id="vat_number"
                                            name="vat_number"
                                            defaultValue={
                                                company.vat_number ?? ''
                                            }
                                        />
                                        <InputError
                                            message={errors.vat_number}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="fiscal_code">
                                            Codice fiscale
                                        </Label>
                                        <Input
                                            id="fiscal_code"
                                            name="fiscal_code"
                                            defaultValue={
                                                company.fiscal_code ?? ''
                                            }
                                        />
                                        <InputError
                                            message={errors.fiscal_code}
                                        />
                                    </div>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="address">Indirizzo</Label>
                                    <Input
                                        id="address"
                                        name="address"
                                        defaultValue={company.address ?? ''}
                                    />
                                    <InputError message={errors.address} />
                                </div>

                                <div className="grid gap-4 sm:grid-cols-4">
                                    <div className="grid gap-2 sm:col-span-2">
                                        <Label htmlFor="city">Città</Label>
                                        <Input
                                            id="city"
                                            name="city"
                                            defaultValue={company.city ?? ''}
                                        />
                                        <InputError message={errors.city} />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="zip">CAP</Label>
                                        <Input
                                            id="zip"
                                            name="zip"
                                            defaultValue={company.zip ?? ''}
                                        />
                                        <InputError message={errors.zip} />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="province">
                                            Provincia
                                        </Label>
                                        <Input
                                            id="province"
                                            name="province"
                                            defaultValue={
                                                company.province ?? ''
                                            }
                                        />
                                        <InputError message={errors.province} />
                                    </div>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="country">Nazione</Label>
                                    <Input
                                        id="country"
                                        name="country"
                                        required
                                        maxLength={2}
                                        className="w-24 uppercase"
                                        defaultValue={company.country ?? 'IT'}
                                        placeholder="IT"
                                    />
                                    <InputError message={errors.country} />
                                </div>

                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div className="grid gap-2">
                                        <Label htmlFor="billing_email">
                                            Email fatturazione
                                        </Label>
                                        <Input
                                            id="billing_email"
                                            type="email"
                                            name="billing_email"
                                            defaultValue={
                                                company.billing_email ?? ''
                                            }
                                        />
                                        <InputError
                                            message={errors.billing_email}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="sdi_code">
                                            Codice SDI
                                        </Label>
                                        <Input
                                            id="sdi_code"
                                            name="sdi_code"
                                            defaultValue={
                                                company.sdi_code ?? ''
                                            }
                                        />
                                        <InputError message={errors.sdi_code} />
                                    </div>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="pec">PEC</Label>
                                    <Input
                                        id="pec"
                                        type="email"
                                        name="pec"
                                        defaultValue={company.pec ?? ''}
                                    />
                                    <InputError message={errors.pec} />
                                </div>
                            </section>

                            <Separator />

                            <section className="space-y-6">
                                <h3 className="text-sm font-medium">
                                    Credenziali Forma.Temp
                                </h3>

                                <p className="text-muted-foreground text-sm">
                                    L&apos;utenza deve essere referente
                                    rilevazione presenze delle giornate del
                                    progetto: è con questa che EasyForma legge
                                    le fasce orarie e compila il registro.
                                </p>

                                <div className="grid gap-2">
                                    <Label htmlFor="formatemp_environment">
                                        Ambiente
                                    </Label>
                                    <Select
                                        name="formatemp_environment"
                                        value={environment}
                                        onValueChange={setEnvironment}
                                    >
                                        <SelectTrigger
                                            id="formatemp_environment"
                                            className="w-full"
                                        >
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {formatempEnvironments.map(
                                                (env) => (
                                                    <SelectItem
                                                        key={env.value}
                                                        value={env.value}
                                                    >
                                                        {env.label}
                                                    </SelectItem>
                                                ),
                                            )}
                                        </SelectContent>
                                    </Select>
                                    <InputError
                                        message={errors.formatemp_environment}
                                    />
                                </div>

                                {environment === 'collaudo' && (
                                    <Alert>
                                        <AlertTriangle />
                                        <AlertTitle>
                                            Ambiente di collaudo: i dati non
                                            arrivano a Forma.Temp
                                        </AlertTitle>
                                        <AlertDescription>
                                            Presenze e consolidamenti finiscono
                                            su FTWEB di collaudo e non hanno
                                            alcun valore ai fini della
                                            rendicontazione. Passa a
                                            &laquo;Produzione&raquo; quando
                                            l&apos;utenza dell&apos;ente è
                                            abilitata sull&apos;ambiente reale.
                                        </AlertDescription>
                                    </Alert>
                                )}

                                <div className="grid gap-2">
                                    <Label htmlFor="formatemp_username">
                                        Nome utente
                                    </Label>
                                    <Input
                                        id="formatemp_username"
                                        name="formatemp_username"
                                        defaultValue={
                                            company.formatemp_username ?? ''
                                        }
                                    />
                                    <InputError
                                        message={errors.formatemp_username}
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="formatemp_password">
                                        Password
                                    </Label>
                                    <PasswordInput
                                        id="formatemp_password"
                                        name="formatemp_password"
                                        autoComplete="new-password"
                                        placeholder={
                                            hasFormatempPassword
                                                ? '••••••• (lascia vuoto per non modificare)'
                                                : ''
                                        }
                                    />
                                    <InputError
                                        message={errors.formatemp_password}
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="formatemp_domain">
                                        Dominio (facoltativo)
                                    </Label>
                                    <Input
                                        id="formatemp_domain"
                                        name="formatemp_domain"
                                        defaultValue={
                                            company.formatemp_domain ?? ''
                                        }
                                        placeholder="es. .rete.forma"
                                    />
                                    <InputError
                                        message={errors.formatemp_domain}
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="formatemp_entity_code">
                                        Codice ente
                                    </Label>
                                    <Input
                                        id="formatemp_entity_code"
                                        name="formatemp_entity_code"
                                        defaultValue={
                                            company.formatemp_entity_code ?? ''
                                        }
                                    />
                                    <InputError
                                        message={errors.formatemp_entity_code}
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="formatemp_fad_platform">
                                        Piattaforma FAD
                                    </Label>
                                    <Input
                                        id="formatemp_fad_platform"
                                        name="formatemp_fad_platform"
                                        defaultValue={
                                            company.formatemp_fad_platform ?? ''
                                        }
                                        placeholder="EasyForma (BigBlueButton)"
                                    />
                                    <InputError
                                        message={errors.formatemp_fad_platform}
                                    />
                                    <p className="text-muted-foreground text-sm">
                                        Usata solo dove FTWEB chiede la
                                        piattaforma FAD: quali registri la
                                        richiedano è da confermare in collaudo.
                                    </p>
                                </div>

                                <div className="flex flex-wrap items-center gap-3">
                                    <Button
                                        type="button"
                                        variant="outline"
                                        disabled={
                                            !hasFormatempPassword ||
                                            !company.formatemp_username
                                        }
                                        onClick={testFormatempConnection}
                                    >
                                        Verifica connessione
                                    </Button>
                                    <p className="text-muted-foreground text-sm">
                                        Salva le credenziali prima di
                                        verificarle.
                                    </p>
                                </div>

                                <InputError message={errors.formatemp} />
                            </section>

                            <div className="flex items-center gap-4">
                                <Button disabled={processing}>Salva</Button>

                                {recentlySuccessful && (
                                    <p className="text-muted-foreground text-sm">
                                        Salvato.
                                    </p>
                                )}
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

CompanySettings.layout = {
    breadcrumbs: [
        {
            title: 'Azienda e Forma.Temp',
            href: edit(),
        },
    ],
};
