import Link from 'next/link';
import { notFound } from 'next/navigation';
import { prisma } from '@/lib/db';
import { requireUser } from '@/lib/auth';
import { Head } from '@/components/desk/Head';
import { StatusBadge } from '@/components/StatusBadge';
import { CONTACT_STATUS, statusTone } from '@/lib/crm';
import { apShort } from '@/lib/ap';
import { updateContact, setStatus, deleteContact } from '../actions';
export const dynamic = 'force-dynamic';

export default async function ContactDetail({ params }: { params: Promise<{ id: string }> }) {
  const u = await requireUser();
  const { id } = await params;
  const c = await prisma.contact.findFirst({ where: { id, userId: u.id }, include: { orders: { orderBy: { createdAt: 'desc' }, select: { id: true, ada: true, parsel: true, mahalle: true, status: true } } } });
  if (!c) notFound();
  const tel = (c.phone || '').replace(/[^\d+]/g, '');
  const wa = tel ? `https://wa.me/${tel.replace(/^\+/, '').replace(/^0/, '90')}` : null;
  return (
    <>
      <Head tag={<Link href="/panel/musteriler" className="hover:underline">‹ Müşteriler</Link>} title={c.name} />
      <div className="flex flex-wrap gap-2 border-t border-ink/15 px-4 py-3">
        {tel && <a href={`tel:${tel}`} className="btn-ink btn-sm">Ara</a>}
        {wa && <a href={wa} target="_blank" rel="noopener" className="btn-line btn-sm">WhatsApp</a>}
        {c.email && <a href={`mailto:${c.email}`} className="btn-line btn-sm">E-posta</a>}
      </div>
      <div className="border-t border-ink/15 px-4 py-3">
        <div className="tag mb-2">Durum</div>
        <div className="flex flex-wrap gap-1.5">
          {CONTACT_STATUS.map((s) => (
            <form key={s.id} action={setStatus.bind(null, c.id, s.id)}>
              <button className={`px-2.5 py-1 text-[12.5px] font-semibold ${c.status === s.id ? statusTone(s.id) + ' ring-2 ring-ink' : 'bg-paper-2 text-ink-soft hover:text-ink'}`}>{s.label}</button>
            </form>
          ))}
        </div>
      </div>
      <div className="border-t border-ink/15 px-4 py-3">
        <div className="tag mb-2">Bağlı ilanlar</div>
        {c.orders.length === 0 ? (
          <p className="text-[13px] text-ink-soft">Bağlı ilan yok. Bir ilan sayfasından “Müşteriye bağla” ile ekleyebilirsiniz.</p>
        ) : (
          <ul className="space-y-1">
            {c.orders.map((o) => (
              <li key={o.id}><Link href={`/panel/siparisler/${o.id}`} className="flex items-center justify-between gap-2 border-b border-ink/10 py-1.5 text-[13.5px] hover:bg-paper-2">
                <b>{o.mahalle} {apShort(o.ada, o.parsel)}</b><StatusBadge s={o.status} /></Link></li>
            ))}
          </ul>
        )}
      </div>
      <form action={updateContact.bind(null, c.id)} className="grid grid-cols-2 gap-2 border-t border-ink/15 px-4 py-4">
        <div className="tag col-span-2">Bilgiler</div>
        <div className="col-span-2"><label className="label">Ad</label><input name="name" defaultValue={c.name} required maxLength={80} className="field" /></div>
        <div><label className="label">Telefon</label><input name="phone" defaultValue={c.phone || ''} maxLength={30} className="field" /></div>
        <div><label className="label">E-posta</label><input name="email" type="email" defaultValue={c.email || ''} maxLength={120} className="field" /></div>
        <input type="hidden" name="status" value={c.status} />
        <div className="col-span-2"><label className="label">Not</label><textarea name="note" defaultValue={c.note || ''} rows={5} maxLength={4000} className="field resize-y leading-relaxed" placeholder="Görüşme notları, bütçe, tercih…" /></div>
        <button className="btn-ink col-span-2">Kaydet</button>
      </form>
      <form action={deleteContact.bind(null, c.id)} className="border-t border-ink/15 px-4 py-4">
        <button className="text-[13px] font-semibold text-survey-dark underline underline-offset-4">Müşteriyi sil</button>
      </form>
    </>
  );
}
