import { Head, Link, usePage } from '@inertiajs/react';
import LeadController from '@/actions/App/Http/Controllers/Admin/LeadController';
import { LeadStatusBadge, WhatsAppBadge } from '@/components/admin/badges';
import { EmptyState } from '@/components/admin/empty-state';
import {
    ListFilters,
    SearchFilter,
    SelectFilter,
} from '@/components/admin/list-filters';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { Pagination } from '@/components/admin/pagination';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useListFilters } from '@/hooks/use-list-filters';
import { dialable } from '@/lib/utils';
import type { Paginated } from '@/types';

type Lead = {
    id: number;
    /** The visitor's name; for a request kept in the CRM, "CRM müşterisi #…". */
    name: string;
    /** Number of the request in the CRM; null for requests stored by the site. */
    crmCustomerId: number | null;
    /** Sent through the short form in front of WhatsApp: the visitor expects the chat. */
    whatsapp: boolean;
    /** Null for requests kept in the CRM (the contact details are there). */
    phone: string | null;
    email: string | null;
    /** Area of interest (category name); null when none was chosen. */
    category: string | null;
    treatment: string | null;
    locale: string;
    status: string;
    createdAt: string | null;
};

type Props = {
    leads: Paginated<Lead>;
    filters: { status: string; search: string };
    statuses: { value: string; label: string }[];
};

export default function LeadIndex({ leads, filters, statuses }: Props) {
    const { locales } = usePage().props;
    const { apply, reset, active } = useListFilters(
        LeadController.index().url,
        filters,
    );

    const statusLabel = (status: string): string =>
        statuses.find((item) => item.value === status)?.label ?? status;

    const languageName = (code: string): string =>
        locales.find((locale) => locale.code === code)?.name ??
        code.toUpperCase();

    return (
        <>
            <Head title="Talepler" />

            <PageContainer>
                <PageHeader
                    title="Talepler"
                    description="Sitedeki iletişim, randevu ve WhatsApp formlarından gelen talepler. Bir talebi açarak durumunu güncelleyebilir ve not ekleyebilirsiniz."
                />

                <ListFilters active={active} onReset={reset}>
                    <SearchFilter
                        key={filters.search}
                        value={filters.search}
                        onSearch={(search) => apply({ search })}
                        label="Ad, telefon, e-posta ya da mesajda ara"
                    />
                    <SelectFilter
                        value={filters.status}
                        onChange={(status) => apply({ status })}
                        label="Durum"
                        allLabel="Tüm durumlar"
                        options={statuses}
                    />
                </ListFilters>

                {leads.data.length === 0 ? (
                    <EmptyState
                        title={
                            active
                                ? 'Bu filtrelere uyan talep yok'
                                : 'Henüz talep yok'
                        }
                        description={
                            active
                                ? 'Aramayı ya da durum filtresini değiştirmeyi deneyin.'
                                : 'Sitedeki iletişim formundan gönderilen talepler burada listelenir.'
                        }
                    />
                ) : (
                    <div className="rounded-xl border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="pl-4">
                                        Ad soyad
                                    </TableHead>
                                    <TableHead>Telefon</TableHead>
                                    <TableHead>
                                        İlgilendiği alan / işlem
                                    </TableHead>
                                    <TableHead>Dil</TableHead>
                                    <TableHead>Durum</TableHead>
                                    <TableHead className="pr-4 text-right">
                                        Tarih
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {leads.data.map((lead) => (
                                    <TableRow key={lead.id}>
                                        <TableCell className="pl-4">
                                            <Link
                                                href={LeadController.show(
                                                    lead.id,
                                                )}
                                                className="font-medium underline-offset-4 hover:underline"
                                            >
                                                {lead.name}
                                            </Link>
                                            {lead.whatsapp && (
                                                <WhatsAppBadge className="ml-2" />
                                            )}
                                            {lead.email && (
                                                <p className="text-xs text-muted-foreground">
                                                    <a
                                                        href={`mailto:${lead.email}`}
                                                        className="underline-offset-4 hover:underline"
                                                    >
                                                        {lead.email}
                                                    </a>
                                                </p>
                                            )}
                                        </TableCell>
                                        <TableCell className="whitespace-nowrap">
                                            {lead.phone ? (
                                                <a
                                                    href={`tel:${dialable(lead.phone)}`}
                                                    className="underline-offset-4 hover:underline"
                                                >
                                                    {lead.phone}
                                                </a>
                                            ) : (
                                                <span className="text-muted-foreground">
                                                    CRM’de
                                                </span>
                                            )}
                                        </TableCell>
                                        <TableCell className="text-muted-foreground">
                                            {lead.category === null &&
                                            lead.treatment === null ? (
                                                '—'
                                            ) : (
                                                <>
                                                    {lead.category && (
                                                        <span className="block">
                                                            {lead.category}
                                                        </span>
                                                    )}
                                                    {lead.treatment && (
                                                        <span className="block text-xs">
                                                            {lead.treatment}
                                                        </span>
                                                    )}
                                                </>
                                            )}
                                        </TableCell>
                                        <TableCell className="text-muted-foreground">
                                            {languageName(lead.locale)}
                                        </TableCell>
                                        <TableCell>
                                            <LeadStatusBadge
                                                status={lead.status}
                                                label={statusLabel(lead.status)}
                                            />
                                        </TableCell>
                                        <TableCell className="pr-4 text-right whitespace-nowrap text-muted-foreground tabular-nums">
                                            {lead.createdAt}
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                )}

                <Pagination paginator={leads} />
            </PageContainer>
        </>
    );
}

LeadIndex.layout = {
    breadcrumbs: [
        {
            title: 'Talepler',
            href: LeadController.index(),
        },
    ],
};
