import { Head, router } from '@inertiajs/react';
import { useState } from 'react';

import { ClientBooleanBadge } from '@/features/clients/components/client-boolean-badge';
import { ClientFormSheet } from '@/features/clients/components/client-form-sheet';
import type { ClientEntity, ClientFormSelectUser } from '@/features/clients/types';
import { useAuthorization } from '@/hooks/use-authorization';
import { useI18n } from '@/hooks/use-i18n';
import { ClientShowLayout } from '@/layouts/clients/client-show-layout';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Icon } from '@/components/ui/icon';
import { Separator } from '@/components/ui/separator';

interface OverviewProps {
    client: ClientEntity;
    client_form_options: {
        portal_users: ClientFormSelectUser[];
        accountants: ClientFormSelectUser[];
    };
}

interface InfoRowProps {
    label: string;
    value: string | null | undefined;
}

function InfoRow({ label, value }: InfoRowProps) {
    if (!value) return null;
    return (
        <div className="flex flex-col gap-0.5 py-2.5 sm:flex-row sm:items-center">
            <span className="w-44 shrink-0 text-sm text-muted-foreground">{label}</span>
            <span className="text-sm font-medium">{value}</span>
        </div>
    );
}

export default function ClientOverviewPage({ client, client_form_options }: OverviewProps) {
    const { t } = useI18n();
    const { can } = useAuthorization();
    const [editOpen, setEditOpen] = useState(false);

    const canEdit = can('edit clients');

    const handleEditClose = () => {
        setEditOpen(false);
        router.reload({ only: ['client'] });
    };

    return (
        <ClientShowLayout client={client}>
            <Head title={client.name} />

            <div className="flex items-center justify-between mb-6">
                <h2 className="text-base font-semibold">{t('clients.show.overview.title')}</h2>
                {canEdit && (
                    <Button size="sm" variant="outline" onClick={() => setEditOpen(true)}>
                        <Icon icon="material-symbols:edit-outline" className="mr-1.5 size-4" />
                        {t('clients.show.overview.edit')}
                    </Button>
                )}
            </div>

            <div className="space-y-6">
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
                            {t('clients.show.overview.section_general')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="divide-y divide-border/50">
                        <InfoRow label={t('clients.show.overview.field_name')} value={client.name} />
                        <InfoRow label="CIF" value={client.cif} />
                        <InfoRow label={t('clients.show.overview.field_trade_register')} value={client.trade_register_number} />
                        <InfoRow label={t('clients.show.overview.field_phone')} value={client.phone} />
                        <InfoRow label={t('clients.show.overview.field_email')} value={client.email} />
                        <div className="flex flex-col gap-0.5 py-2.5 sm:flex-row sm:items-center">
                            <span className="w-44 shrink-0 text-sm text-muted-foreground">{t('clients.show.overview.field_vat')}</span>
                            <ClientBooleanBadge
                                value={client.is_vat_payer}
                                trueLabel={t('clients.show.overview.vat_yes')}
                                falseLabel={t('clients.show.overview.vat_no')}
                            />
                        </div>
                        <div className="flex flex-col gap-0.5 py-2.5 sm:flex-row sm:items-center">
                            <span className="w-44 shrink-0 text-sm text-muted-foreground">{t('clients.show.overview.field_type')}</span>
                            <ClientBooleanBadge
                                value={client.is_individual}
                                trueLabel={t('clients.show.overview.type_individual')}
                                falseLabel={t('clients.show.overview.type_company')}
                                trueVariant="infoSoft"
                                falseVariant="secondarySoft"
                            />
                        </div>
                        <div className="flex flex-col gap-0.5 py-2.5 sm:flex-row sm:items-center">
                            <span className="w-44 shrink-0 text-sm text-muted-foreground">{t('clients.show.overview.field_status')}</span>
                            <ClientBooleanBadge
                                value={client.active}
                                trueLabel={t('clients.show.overview.status_active')}
                                falseLabel={t('clients.show.overview.status_inactive')}
                                falseVariant="destructiveSoft"
                            />
                        </div>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
                            {t('clients.show.overview.section_address')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="divide-y divide-border/50">
                        <InfoRow label={t('clients.show.overview.field_country')} value={client.country} />
                        <InfoRow label={t('clients.show.overview.field_county')} value={client.county} />
                        <InfoRow label={t('clients.show.overview.field_city')} value={client.city} />
                        <InfoRow label={t('clients.show.overview.field_address')} value={client.address} />
                    </CardContent>
                </Card>

                {client.contacts.length > 0 && (
                    <Card>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
                                {t('clients.show.overview.section_contacts')}
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="divide-y divide-border/50">
                            {client.contacts.map((contact) => (
                                <div key={contact.id} className="py-3">
                                    <div className="flex items-center gap-2">
                                        <span className="font-medium text-sm">{contact.name}</span>
                                        {contact.is_primary && (
                                            <Badge variant="primarySoft" className="text-[10px] px-1.5 py-0">
                                                {t('clients.show.overview.contact_primary')}
                                            </Badge>
                                        )}
                                    </div>
                                    <div className="mt-0.5 flex flex-wrap gap-x-4 gap-y-0.5">
                                        {contact.position && (
                                            <span className="text-xs text-muted-foreground">{contact.position}</span>
                                        )}
                                        {contact.email && (
                                            <span className="text-xs text-muted-foreground">{contact.email}</span>
                                        )}
                                        {contact.phone && (
                                            <span className="text-xs text-muted-foreground">{contact.phone}</span>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                )}
            </div>

            {canEdit && (
                <ClientFormSheet
                    open={editOpen}
                    onOpenChange={(open) => { if (!open) handleEditClose(); else setEditOpen(true); }}
                    mode="edit"
                    client={client}
                    accountants={client_form_options.accountants}
                    canManageContacts={can('manage client contacts')}
                    canAssignAccountants={can('assign client accountants')}
                    onAfterSave={handleEditClose}
                />
            )}
        </ClientShowLayout>
    );
}
