import InputError from '@/Components/InputError';
import InputLabel from '@/Components/InputLabel';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { PageProps } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { FormEventHandler, ReactNode } from 'react';

type Settings = {
    organization_name: string;
    email: string | null;
    phone: string | null;
    address: string | null;
    city: string | null;
    postal_code: string | null;
    country: string;
    timezone: string;
    language: string;
    currency: string;
    items_per_page: number;
};

type Props = PageProps<{ settings: Settings; flash?: { success?: string | null } }>;

export default function SettingsEdit({ settings, flash }: Props) {
    const form = useForm({
        organization_name: settings.organization_name,
        email: settings.email ?? '',
        phone: settings.phone ?? '',
        address: settings.address ?? '',
        city: settings.city ?? '',
        postal_code: settings.postal_code ?? '',
        country: settings.country,
        timezone: settings.timezone,
        language: settings.language,
        currency: settings.currency,
        items_per_page: (settings.items_per_page ?? 25).toString(),
    });
    const submit: FormEventHandler = (event) => {
        event.preventDefault();
        form.patch(route('settings.update'));
    };

    return (
        <AuthenticatedLayout header={<div><h1 className="text-2xl font-bold text-[#062853]">Paramètres</h1><p className="mt-1 text-sm text-slate-500">Gérez les paramètres de votre organisation</p></div>}>
            <Head title="Paramètres CRM" />
            <div className="mx-auto max-w-[1250px] space-y-5 px-4 py-5 sm:px-6 lg:px-7">
                {flash?.success && <div className="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">{flash.success}</div>}
                <form onSubmit={submit} className="grid gap-5 lg:grid-cols-2">
                    <Panel title="Informations générales">
                        <Field label="Nom de l'organisation" id="settings_organization"><TextInput id="settings_organization" value={form.data.organization_name} onChange={(event) => form.setData('organization_name', event.target.value)} className="mt-1 w-full" /><InputError message={form.errors.organization_name} className="mt-1" /></Field>
                        <Field label="Email principal" id="settings_email"><TextInput id="settings_email" type="email" value={form.data.email} onChange={(event) => form.setData('email', event.target.value)} className="mt-1 w-full" /></Field>
                        <Field label="Téléphone" id="settings_phone"><TextInput id="settings_phone" value={form.data.phone} onChange={(event) => form.setData('phone', event.target.value)} className="mt-1 w-full" /></Field>
                    </Panel>
                    <Panel title="Localisation">
                        <Field label="Adresse" id="settings_address"><TextInput id="settings_address" value={form.data.address} onChange={(event) => form.setData('address', event.target.value)} className="mt-1 w-full" /></Field>
                        <div className="grid grid-cols-[120px_1fr] gap-3">
                            <Field label="Code postal" id="settings_postal_code"><TextInput id="settings_postal_code" value={form.data.postal_code} onChange={(event) => form.setData('postal_code', event.target.value)} className="mt-1 w-full" /></Field>
                            <Field label="Ville" id="settings_city"><TextInput id="settings_city" value={form.data.city} onChange={(event) => form.setData('city', event.target.value)} className="mt-1 w-full" /></Field>
                        </div>
                    </Panel>
                    <Panel title="Préférences">
                        <div className="grid grid-cols-2 gap-3">
                            <SelectField label="Langue" id="settings_language" value={form.data.language} onChange={(value) => form.setData('language', value)} options={{ fr: 'Français', en: 'English' }} />
                            <SelectField label="Devise" id="settings_currency" value={form.data.currency} onChange={(value) => form.setData('currency', value)} options={{ EUR: 'Euro (€)', CHF: 'Franc suisse' }} />
                            <SelectField label="Fuseau horaire" id="settings_timezone" value={form.data.timezone} onChange={(value) => form.setData('timezone', value)} options={{ 'Europe/Paris': 'Paris', 'Europe/Brussels': 'Bruxelles', 'Europe/Zurich': 'Zurich' }} />
                            <SelectField label="Lignes par page" id="settings_items" value={form.data.items_per_page} onChange={(value) => form.setData('items_per_page', value)} options={{ '10': '10', '25': '25', '50': '50', '100': '100' }} />
                        </div>
                    </Panel>
                    <Panel title="Intégrations connectées">
                        <div className="grid grid-cols-3 gap-3">
                            {['Téléplus.fr', 'Google Workspace', 'Outlook'].map((integration) => (
                                <div key={integration} className="rounded-lg border border-slate-200 p-4 text-center">
                                    <p className="text-sm font-semibold">{integration}</p>
                                    <p className="mt-2 text-xs font-semibold text-emerald-700">Connecté</p>
                                </div>
                            ))}
                        </div>
                    </Panel>
                    <div className="lg:col-span-2">
                        <PrimaryButton disabled={form.processing}>Enregistrer les paramètres</PrimaryButton>
                    </div>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}

function Panel({ title, children }: { title: string; children: ReactNode }) { return <section className="space-y-4 rounded-xl border border-slate-200 bg-white p-5 shadow-sm"><h2 className="text-sm font-bold uppercase tracking-wide text-[#062853]">{title}</h2>{children}</section>; }
function Field({ label, id, children }: { label: string; id: string; children: ReactNode }) { return <div><InputLabel htmlFor={id} value={label} />{children}</div>; }
function SelectField({ label, id, value, onChange, options }: { label: string; id: string; value: string; onChange: (value: string) => void; options: Record<string, string> }) { return <Field label={label} id={id}><select id={id} value={value} onChange={(event) => onChange(event.target.value)} className="mt-1 w-full rounded-lg border-slate-200 text-sm">{Object.entries(options).map(([option, name]) => <option key={option} value={option}>{name}</option>)}</select></Field>; }
