import { Form, Head, Link, usePage } from '@inertiajs/react';
import { Trash2 } from 'lucide-react';
import type { ReactNode } from 'react';
import CategoryController from '@/actions/App/Http/Controllers/Admin/CategoryController';
import LeadController from '@/actions/App/Http/Controllers/Admin/LeadController';
import TreatmentController from '@/actions/App/Http/Controllers/Admin/TreatmentController';
import { ConfirmDialog } from '@/components/admin/confirm-dialog';
import { ExternalLink } from '@/components/admin/external-link';
import { FormSection } from '@/components/admin/form-section';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import { Textarea } from '@/components/ui/textarea';
import { dialable } from '@/lib/utils';

type Props = {
    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;
        /** The form it came through: the request form, or the short form in front of WhatsApp. */
        channel: { value: 'form' | 'whatsapp'; label: string };
        /** Null for requests kept in the CRM (the contact details are there). */
        phone: string | null;
        email: string | null;
        message: string | null;
        /** Area of interest (treatment category). */
        category: { id: number; name: string } | null;
        treatment: { id: number; name: string } | null;
        locale: string;
        sourcePath: string | null;
        consentAt: string | null;
        createdAt: string | null;
        updatedAt: string | null;
        ipAddress: string | null;
        userAgent: string | null;
        status: string;
        note: string | null;
    };
    statuses: { value: string; label: string }[];
};

export default function LeadShow({ lead, statuses }: Props) {
    const { locales } = usePage().props;

    const language =
        locales.find((locale) => locale.code === lead.locale)?.name ??
        lead.locale.toUpperCase();

    return (
        <>
            <Head title={`Talep: ${lead.name}`} />

            <PageContainer>
                <PageHeader
                    title={lead.name}
                    description={`${lead.createdAt ?? ''} tarihinde gönderildi.`}
                    actions={
                        <ConfirmDialog
                            action={LeadController.destroy.form(lead.id)}
                            title="Talep silinsin mi?"
                            description={`${lead.name} adına gelen talep ve notunuz kalıcı olarak silinir. Bu işlem geri alınamaz.`}
                        >
                            <Button variant="outline" size="sm">
                                <Trash2 />
                                Talebi sil
                            </Button>
                        </ConfirmDialog>
                    }
                />

                <div className="grid grid-cols-1 items-start gap-6 lg:grid-cols-3">
                    <FormSection
                        title="Gönderilen bilgiler"
                        description={
                            lead.crmCustomerId === null
                                ? 'Ziyaretçinin formda yazdıkları; değiştirilemez.'
                                : 'Talep CRM’e gönderildi; ad ve telefon oradadır. Burada ziyaretçinin formdan sonra seçtiği alan ve işlem durur.'
                        }
                        className="lg:col-span-2"
                    >
                        <dl className="grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2">
                            {lead.crmCustomerId !== null && (
                                <Detail label="CRM müşteri no">
                                    {lead.crmCustomerId}
                                </Detail>
                            )}
                            <Detail label="Telefon">
                                {lead.phone ? (
                                    <a
                                        href={`tel:${dialable(lead.phone)}`}
                                        className="underline underline-offset-4"
                                    >
                                        {lead.phone}
                                    </a>
                                ) : (
                                    <Empty>CRM’de</Empty>
                                )}
                            </Detail>
                            <Detail label="E-posta">
                                {lead.email ? (
                                    <a
                                        href={`mailto:${lead.email}`}
                                        className="break-all underline underline-offset-4"
                                    >
                                        {lead.email}
                                    </a>
                                ) : (
                                    <Empty>Belirtilmedi</Empty>
                                )}
                            </Detail>
                            <Detail label="İlgilendiği alan">
                                {lead.category ? (
                                    <Link
                                        href={CategoryController.edit(
                                            lead.category.id,
                                        )}
                                        className="underline underline-offset-4"
                                    >
                                        {lead.category.name}
                                    </Link>
                                ) : (
                                    <Empty>Seçilmedi</Empty>
                                )}
                            </Detail>
                            <Detail label="İlgilendiği işlem">
                                {lead.treatment ? (
                                    <Link
                                        href={TreatmentController.edit(
                                            lead.treatment.id,
                                        )}
                                        className="underline underline-offset-4"
                                    >
                                        {lead.treatment.name}
                                    </Link>
                                ) : (
                                    <Empty>Seçilmedi</Empty>
                                )}
                            </Detail>
                            <Detail label="Formun dili">{language}</Detail>
                            <Detail label="Geldiği form">
                                {lead.channel.label}
                                {lead.channel.value === 'whatsapp' && (
                                    <span className="mt-1 block text-xs text-muted-foreground">
                                        Ziyaretçi ad ve telefon bırakıp
                                        WhatsApp’a yönlendirildi; sohbet
                                        bekliyor.
                                    </span>
                                )}
                            </Detail>
                            <Detail label="Mesaj" wide>
                                {lead.message ? (
                                    <p className="whitespace-pre-wrap">
                                        {lead.message}
                                    </p>
                                ) : (
                                    <Empty>Mesaj yazılmadı</Empty>
                                )}
                            </Detail>
                            <Detail label="Talebin gönderildiği sayfa">
                                {/* Taken from the Referer header: only a path on this site is linked. */}
                                {lead.sourcePath &&
                                /^\/(?!\/)/.test(lead.sourcePath) ? (
                                    <ExternalLink
                                        href={lead.sourcePath}
                                        className="break-all"
                                    >
                                        {lead.sourcePath}
                                    </ExternalLink>
                                ) : (
                                    <Empty>Bilinmiyor</Empty>
                                )}
                            </Detail>
                            <Detail label="Aydınlatma metni onayı">
                                {lead.consentAt ?? <Empty>Kayıt yok</Empty>}
                            </Detail>
                            <Detail label="IP adresi">
                                {lead.ipAddress ?? <Empty>Kayıt yok</Empty>}
                            </Detail>
                            <Detail label="Tarayıcı">
                                {lead.userAgent ? (
                                    <span className="text-xs break-all text-muted-foreground">
                                        {lead.userAgent}
                                    </span>
                                ) : (
                                    <Empty>Kayıt yok</Empty>
                                )}
                            </Detail>
                        </dl>
                    </FormSection>

                    <FormSection
                        title="Durum ve not"
                        description="Yalnızca panelde görünür; ziyaretçiye gösterilmez."
                    >
                        <Form
                            {...LeadController.update.form(lead.id)}
                            options={{ preserveScroll: true }}
                            className="grid grid-cols-1 gap-6"
                        >
                            {({ processing, errors }) => (
                                <>
                                    <div className="grid grid-cols-1 gap-2">
                                        <Label htmlFor="status">Durum</Label>
                                        <Select
                                            name="status"
                                            defaultValue={lead.status}
                                        >
                                            <SelectTrigger
                                                id="status"
                                                className="w-full"
                                            >
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {statuses.map((status) => (
                                                    <SelectItem
                                                        key={status.value}
                                                        value={status.value}
                                                    >
                                                        {status.label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <InputError message={errors.status} />
                                    </div>

                                    <div className="grid grid-cols-1 gap-2">
                                        <Label htmlFor="note">Not</Label>
                                        <Textarea
                                            id="note"
                                            name="note"
                                            rows={5}
                                            defaultValue={lead.note ?? ''}
                                            placeholder="Görüşme notu, randevu tarihi…"
                                        />
                                        <InputError message={errors.note} />
                                    </div>

                                    <div className="flex items-center gap-4">
                                        <Button disabled={processing}>
                                            {processing && <Spinner />}
                                            Kaydet
                                        </Button>
                                        {lead.updatedAt && (
                                            <p className="text-xs text-muted-foreground">
                                                Son güncelleme: {lead.updatedAt}
                                            </p>
                                        )}
                                    </div>
                                </>
                            )}
                        </Form>
                    </FormSection>
                </div>
            </PageContainer>
        </>
    );
}

function Detail({
    label,
    wide = false,
    children,
}: {
    label: string;
    wide?: boolean;
    children: ReactNode;
}) {
    return (
        <div className={wide ? 'sm:col-span-2' : undefined}>
            <dt className="text-xs font-medium text-muted-foreground">
                {label}
            </dt>
            <dd className="mt-1 text-sm">{children}</dd>
        </div>
    );
}

function Empty({ children }: { children: ReactNode }) {
    return <span className="text-muted-foreground">{children}</span>;
}

LeadShow.layout = (props: Props) => ({
    breadcrumbs: [
        { title: 'Talepler', href: LeadController.index() },
        { title: props.lead.name, href: LeadController.show(props.lead.id) },
    ],
});
