import { Plus, Trash2 } from 'lucide-react';
import type { Dispatch, SetStateAction } from 'react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import type { ClientFormDraft } from '@/features/clients/lib/client-form-draft';
import {
    emptyClientFormContact,
    fixClientFormPrimaryContact,
} from '@/features/clients/lib/client-form-draft';
import type { ClientFormSelectUser } from '@/features/clients/types';

type Translate = (key: string, params?: Record<string, string | number>) => string;

type SectionProps = {
    form: ClientFormDraft;
    setForm: Dispatch<SetStateAction<ClientFormDraft>>;
    t: Translate;
};

export function ClientFormGeneralSection({ form, setForm, t }: SectionProps) {
    return (
        <div className="space-y-6">
            <p className="text-xs text-muted-foreground leading-relaxed">{t('clients.admin_form.hints.general')}</p>

            <div className="space-y-3">
                <h3 className="text-sm font-semibold">{t('clients.admin_form.sections.identification')}</h3>
                <div className="grid gap-3 sm:grid-cols-2">
                    <div className="space-y-2 sm:col-span-2">
                        <Label htmlFor="client-name">{t('clients.admin_form.fields.name')}</Label>
                        <Input
                            id="client-name"
                            value={form.name}
                            onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
                            autoComplete="organization"
                        />
                    </div>
                    <div className="flex items-center justify-between gap-3 rounded-lg border border-border px-3 py-2">
                        <div>
                            <p className="text-sm font-medium">{t('clients.admin_form.switches.individual_label')}</p>
                            <p className="text-xs text-muted-foreground">{t('clients.admin_form.switches.individual_hint')}</p>
                        </div>
                        <Switch
                            checked={form.is_individual}
                            onCheckedChange={(v) => setForm((p) => ({ ...p, is_individual: Boolean(v) }))}
                        />
                    </div>
                    <div className="flex items-center justify-between gap-3 rounded-lg border border-border px-3 py-2">
                        <p className="text-sm font-medium">{t('clients.admin_form.switches.vat_payer')}</p>
                        <Switch
                            checked={form.is_vat_payer}
                            onCheckedChange={(v) => setForm((p) => ({ ...p, is_vat_payer: Boolean(v) }))}
                        />
                    </div>
                    <div className="flex items-center justify-between gap-3 rounded-lg border border-border px-3 py-2 sm:col-span-2">
                        <p className="text-sm font-medium">{t('clients.admin_form.switches.client_active')}</p>
                        <Switch checked={form.active} onCheckedChange={(v) => setForm((p) => ({ ...p, active: Boolean(v) }))} />
                    </div>
                </div>
            </div>

            {!form.is_individual ? (
                <div className="space-y-3">
                    <h3 className="text-sm font-semibold">{t('clients.admin_form.sections.registry')}</h3>
                    <div className="grid gap-3 sm:grid-cols-2">
                        <div className="space-y-2">
                            <Label htmlFor="client-cif">{t('clients.admin_form.fields.cif')}</Label>
                            <Input id="client-cif" value={form.cif} onChange={(e) => setForm((p) => ({ ...p, cif: e.target.value }))} />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="client-rc">{t('clients.admin_form.fields.trade_register')}</Label>
                            <Input
                                id="client-rc"
                                value={form.trade_register_number}
                                onChange={(e) => setForm((p) => ({ ...p, trade_register_number: e.target.value }))}
                            />
                        </div>
                    </div>
                </div>
            ) : null}
        </div>
    );
}

export function ClientFormLocationSection({ form, setForm, t }: SectionProps) {
    return (
        <div className="space-y-6">
            <p className="text-xs text-muted-foreground leading-relaxed">{t('clients.admin_form.hints.location')}</p>

            <div className="space-y-3">
                <h3 className="text-sm font-semibold">{t('clients.admin_form.sections.contact')}</h3>
                <div className="grid gap-3 sm:grid-cols-2">
                    <div className="space-y-2">
                        <Label htmlFor="client-email">{t('clients.admin_form.fields.email')}</Label>
                        <Input
                            id="client-email"
                            type="email"
                            value={form.email}
                            onChange={(e) => setForm((p) => ({ ...p, email: e.target.value }))}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="client-phone">{t('clients.admin_form.fields.phone')}</Label>
                        <Input id="client-phone" value={form.phone} onChange={(e) => setForm((p) => ({ ...p, phone: e.target.value }))} />
                    </div>
                </div>
            </div>

            <div className="space-y-3">
                <h3 className="text-sm font-semibold">{t('clients.admin_form.sections.address')}</h3>
                <div className="grid gap-3 sm:grid-cols-2">
                    <div className="space-y-2">
                        <Label htmlFor="client-country">{t('clients.admin_form.fields.country')}</Label>
                        <Input id="client-country" value={form.country} onChange={(e) => setForm((p) => ({ ...p, country: e.target.value }))} />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="client-county">{t('clients.admin_form.fields.county')}</Label>
                        <Input id="client-county" value={form.county} onChange={(e) => setForm((p) => ({ ...p, county: e.target.value }))} />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="client-city">{t('clients.admin_form.fields.city')}</Label>
                        <Input id="client-city" value={form.city} onChange={(e) => setForm((p) => ({ ...p, city: e.target.value }))} />
                    </div>
                    <div className="space-y-2 sm:col-span-2">
                        <Label htmlFor="client-address">{t('clients.admin_form.fields.address')}</Label>
                        <Textarea
                            id="client-address"
                            rows={3}
                            value={form.address}
                            onChange={(e) => setForm((p) => ({ ...p, address: e.target.value }))}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
}

export function ClientFormContactsSection({ form, setForm, t }: SectionProps) {
    return (
        <div className="space-y-4">
            <p className="text-xs text-muted-foreground leading-relaxed">{t('clients.admin_form.hints.contacts')}</p>

            <div className="flex items-center justify-between gap-2">
                <h3 className="text-sm font-semibold">{t('clients.admin_form.sections.contacts')}</h3>
                <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="h-8 gap-1 px-2 text-primary"
                    onClick={() =>
                        setForm((p) => ({
                            ...p,
                            contacts: fixClientFormPrimaryContact([...p.contacts, emptyClientFormContact()]),
                        }))
                    }
                >
                    <Plus className="size-4" />
                    {t('clients.admin_form.contacts.add')}
                </Button>
            </div>

            <div className="space-y-4">
                {form.contacts.map((row, index) => (
                    <div key={row.rowKey} className="space-y-3 rounded-lg border border-border p-3">
                        <div className="flex items-center justify-between gap-2">
                            <span className="text-xs font-medium text-muted-foreground">
                                {t('clients.admin_form.contacts.contact_label', { num: index + 1 })}
                            </span>
                            <div className="flex items-center gap-2">
                                <div className="flex items-center gap-2">
                                    <Checkbox
                                        id={`primary-${row.rowKey}`}
                                        checked={row.is_primary}
                                        onCheckedChange={(v) => {
                                            const checked = v === true;

                                            if (checked) {
                                                setForm((p) => ({
                                                    ...p,
                                                    contacts: p.contacts.map((c) => ({
                                                        ...c,
                                                        is_primary: c.rowKey === row.rowKey,
                                                    })),
                                                }));
                                            } else {
                                                setForm((p) => ({
                                                    ...p,
                                                    contacts: p.contacts.map((c) =>
                                                        c.rowKey === row.rowKey ? { ...c, is_primary: false } : c,
                                                    ),
                                                }));
                                            }
                                        }}
                                    />
                                    <Label htmlFor={`primary-${row.rowKey}`} className="cursor-pointer text-xs font-normal">
                                        {t('clients.admin_form.contacts.primary')}
                                    </Label>
                                </div>
                                {form.contacts.length > 1 ? (
                                    <button
                                        type="button"
                                        className="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-muted"
                                        aria-label={t('clients.admin_form.contacts.delete_aria')}
                                        onClick={() =>
                                            setForm((p) => {
                                                const next = p.contacts.filter((c) => c.rowKey !== row.rowKey);

                                                return {
                                                    ...p,
                                                    contacts: next.length ? fixClientFormPrimaryContact(next) : [emptyClientFormContact()],
                                                };
                                            })
                                        }
                                    >
                                        <Trash2 className="size-4" />
                                    </button>
                                ) : null}
                            </div>
                        </div>
                        <div className="grid gap-3 sm:grid-cols-2">
                            <div className="space-y-2 sm:col-span-2">
                                <Label>{t('clients.admin_form.fields.contact_name')}</Label>
                                <Input
                                    value={row.name}
                                    onChange={(e) =>
                                        setForm((p) => ({
                                            ...p,
                                            contacts: p.contacts.map((c) => (c.rowKey === row.rowKey ? { ...c, name: e.target.value } : c)),
                                        }))
                                    }
                                />
                            </div>
                            <div className="space-y-2">
                                <Label>{t('clients.admin_form.fields.contact_email')}</Label>
                                <Input
                                    type="email"
                                    value={row.email}
                                    onChange={(e) =>
                                        setForm((p) => ({
                                            ...p,
                                            contacts: p.contacts.map((c) => (c.rowKey === row.rowKey ? { ...c, email: e.target.value } : c)),
                                        }))
                                    }
                                />
                            </div>
                            <div className="space-y-2">
                                <Label>{t('clients.admin_form.fields.contact_phone')}</Label>
                                <Input
                                    value={row.phone}
                                    onChange={(e) =>
                                        setForm((p) => ({
                                            ...p,
                                            contacts: p.contacts.map((c) => (c.rowKey === row.rowKey ? { ...c, phone: e.target.value } : c)),
                                        }))
                                    }
                                />
                            </div>
                            <div className="space-y-2 sm:col-span-2">
                                <Label>{t('clients.admin_form.fields.contact_position')}</Label>
                                <Input
                                    value={row.position}
                                    onChange={(e) =>
                                        setForm((p) => ({
                                            ...p,
                                            contacts: p.contacts.map((c) =>
                                                c.rowKey === row.rowKey ? { ...c, position: e.target.value } : c,
                                            ),
                                        }))
                                    }
                                />
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}

type AccountantsSectionProps = SectionProps & {
    accountants: ClientFormSelectUser[];
};

export function ClientFormAccountantsSection({ form, setForm, accountants, t }: AccountantsSectionProps) {
    return (
        <div className="space-y-4">
            <p className="text-xs text-muted-foreground leading-relaxed">{t('clients.admin_form.hints.accountants')}</p>

            <h3 className="text-sm font-semibold">{t('clients.admin_form.sections.accountants')}</h3>
            <div className="max-h-[min(50vh,320px)] space-y-2 overflow-y-auto rounded-lg border border-border p-2">
                {accountants.length === 0 ? (
                    <p className="text-sm text-muted-foreground">{t('clients.admin_form.contacts.no_accountants')}</p>
                ) : (
                    accountants.map((u) => (
                        <label key={u.id} className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted/60">
                            <Checkbox
                                checked={form.accountant_user_ids.includes(u.id)}
                                onCheckedChange={(v) => {
                                    const checked = v === true;
                                    setForm((p) => ({
                                        ...p,
                                        accountant_user_ids: checked
                                            ? [...p.accountant_user_ids, u.id]
                                            : p.accountant_user_ids.filter((id) => id !== u.id),
                                    }));
                                }}
                            />
                            <span className="text-sm">
                                {u.name}
                                {u.email ? <span className="text-muted-foreground"> — {u.email}</span> : null}
                            </span>
                        </label>
                    ))
                )}
            </div>
        </div>
    );
}
