import AppLayout from '@/Layouts/AppLayout';
import { sanitizeZengin } from '@/Components/RichTextEditor';
import Link from '@/Components/Link';
import { Head } from '@inertiajs/react';
import { useYetki } from '@/lib/yetki';
import SozlesmeIletModal from '@/Pages/MusteriSozlesme/_IletModal';
import { ArrowLeft, Download, FileText, Printer, Send } from 'lucide-react';
import { useState } from 'react';

interface Props {
    musteri: { id: number; unvan: string };
    sozlesme: {
        id: number;
        sozlesme_kod: string;
        sozlesme_ad: string;
        icerik: string;
        imza_ad_soyad: string;
        imza: string;
        onay_tarihi?: string | null;
        onaylayan?: string | null;
        ip_adresi?: string | null;
    };
}

export default function MusteriSozlesmeGoster({ musteri, sozlesme }: Props) {
    const { can } = useYetki();
    const [iletAcik, setIletAcik] = useState(false);
    const tarih = sozlesme.onay_tarihi
        ? new Date(sozlesme.onay_tarihi).toLocaleString('tr-TR', {
            day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit',
        })
        : '—';

    return (
        <AppLayout
            title={`${sozlesme.sozlesme_ad} — ${musteri.unvan}`}
            actions={
                <div className="flex items-center gap-2">
                    <Link href={`/musteriler/${musteri.id}/sozlesmeler/`}
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        <ArrowLeft className="h-4 w-4" /> Sözleşmeler
                    </Link>
                    <button type="button" onClick={() => window.print()}
                        title="Tarayıcıdan yazdır"
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        <Printer className="h-4 w-4" /> Yazdır
                    </button>
                    <a href={`/musteriler/${musteri.id}/sozlesmeler/${sozlesme.id}/pdf/?goruntule=1`}
                        target="_blank" rel="noopener"
                        title="PDF olarak görüntüle"
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        <FileText className="h-4 w-4" /> <span className="hidden md:inline">PDF Görüntüle</span>
                    </a>
                    <a href={`/musteriler/${musteri.id}/sozlesmeler/${sozlesme.id}/pdf/`}
                        title="PDF olarak indir"
                        className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        <Download className="h-4 w-4" /> <span className="hidden md:inline">PDF İndir</span>
                    </a>
                    {can('musteri_sozlesme.ekle') && (
                        <button type="button" onClick={() => setIletAcik(true)}
                            className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-blue-600 px-3 text-sm font-semibold text-white shadow-sm hover:bg-blue-700">
                            <Send className="h-4 w-4" /> Müşteriye İlet
                        </button>
                    )}
                </div>
            }
        >
            <Head title={`${sozlesme.sozlesme_ad} — ${musteri.unvan}`} />

            {/* Yazdırırken sadece belge görünür */}
            <style>{`
                @media print {
                    body * { visibility: hidden; }
                    #sozlesme-belge, #sozlesme-belge * { visibility: visible; }
                    #sozlesme-belge { position: absolute; left: 0; top: 0; width: 100%; padding: 0; box-shadow: none; border: 0; }
                    .yazdirma-gizle { display: none !important; }
                }
            `}</style>

            <div className="mx-auto max-w-4xl">
                {/* Üst bilgi kartı — yazdırmada gizlenir */}
                <div className="yazdirma-gizle mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-slate-200 bg-white p-4">
                    <span className="rounded bg-slate-100 px-2 py-1 font-mono text-xs font-medium text-slate-700">
                        {sozlesme.sozlesme_kod}
                    </span>
                    <div className="min-w-0 flex-1">
                        <div className="truncate text-sm font-semibold text-slate-900">{sozlesme.sozlesme_ad}</div>
                        <div className="truncate text-xs text-slate-500">{musteri.unvan}</div>
                    </div>
                    <div className="text-right text-xs text-slate-500">
                        <div>Onay: <span className="font-medium text-slate-700">{tarih}</span></div>
                        {sozlesme.onaylayan && <div>İşlemi yapan: {sozlesme.onaylayan}</div>}
                    </div>
                </div>

                {/* BELGE */}
                <div id="sozlesme-belge" className="rounded-xl bg-white px-10 py-9 shadow-sm ring-1 ring-slate-200">
                    <div className="mb-6 border-b border-slate-200 pb-4">
                        <h1 className="text-xl font-bold text-slate-900">{sozlesme.sozlesme_ad}</h1>
                        <p className="mt-1 text-xs text-slate-500">
                            Sözleşme No: {sozlesme.sozlesme_kod} · {musteri.unvan}
                        </p>
                    </div>

                    {/* Onaylandığı andaki metin — sonradan DEĞİŞMEZ */}
                    <div
                        className="sozlesme-metni text-[13.5px] leading-[1.85] text-slate-800
                            [&_h1]:mb-2 [&_h1]:mt-6 [&_h1]:text-base [&_h1]:font-bold [&_h1]:text-slate-900
                            [&_h2]:mb-2 [&_h2]:mt-6 [&_h2]:text-[15px] [&_h2]:font-bold [&_h2]:text-slate-900
                            [&_h3]:mb-1.5 [&_h3]:mt-5 [&_h3]:text-[13.5px] [&_h3]:font-semibold [&_h3]:text-slate-900
                            [&_h4]:mb-1.5 [&_h4]:mt-4 [&_h4]:text-[13px] [&_h4]:font-semibold
                            [&_p]:mb-3 [&_p]:text-justify
                            [&_ul]:mb-3 [&_ul]:list-disc [&_ul]:pl-6 [&_ol]:mb-3 [&_ol]:list-decimal [&_ol]:pl-6
                            [&_li]:mb-1
                            [&_strong]:font-semibold [&_strong]:text-slate-900
                            [&_a]:text-blue-600 [&_a]:underline
                            [&_hr]:my-5 [&_hr]:border-slate-200
                            [&_blockquote]:my-3 [&_blockquote]:border-l-4 [&_blockquote]:border-slate-300 [&_blockquote]:pl-4 [&_blockquote]:italic [&_blockquote]:text-slate-600
                            [&_table]:my-3 [&_table]:w-full [&_table]:border-collapse
                            [&_td]:border [&_td]:border-slate-300 [&_td]:p-2 [&_td]:align-top
                            [&_th]:border [&_th]:border-slate-300 [&_th]:bg-slate-50 [&_th]:p-2 [&_th]:text-left [&_th]:font-semibold
                            [&_img]:my-3 [&_img]:max-w-full [&_img]:rounded
                            [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded [&_pre]:bg-slate-100 [&_pre]:p-3 [&_pre]:font-mono [&_pre]:text-xs"
                        dangerouslySetInnerHTML={{ __html: sanitizeZengin(sozlesme.icerik) }}
                    />

                    {/* İmza bloğu */}
                    <div className="mt-10 border-t border-slate-200 pt-6">
                        <div className="flex flex-wrap items-end justify-between gap-6">
                            <div>
                                <div className="mb-2 text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    İmza
                                </div>
                                {sozlesme.imza ? (
                                    <img
                                        src={sozlesme.imza}
                                        alt="İmza"
                                        className="h-24 w-auto max-w-[320px] object-contain"
                                    />
                                ) : (
                                    <div className="text-sm text-slate-400">İmza bulunamadı.</div>
                                )}
                                <div className="mt-2 border-t border-slate-300 pt-1 text-sm font-medium text-slate-900">
                                    {sozlesme.imza_ad_soyad}
                                </div>
                            </div>

                            <div className="text-right text-xs text-slate-600">
                                <div>Onay Tarihi: <span className="font-medium">{tarih}</span></div>
                                {sozlesme.ip_adresi && <div className="mt-0.5">IP: {sozlesme.ip_adresi}</div>}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <SozlesmeIletModal
                kayit={iletAcik ? {
                    id: sozlesme.id,
                    sozlesme_kod: sozlesme.sozlesme_kod,
                    sozlesme_ad: sozlesme.sozlesme_ad,
                    imza_ad_soyad: sozlesme.imza_ad_soyad,
                } : null}
                musteri={musteri}
                onClose={() => setIletAcik(false)}
            />
        </AppLayout>
    );
}
