import Link from "next/link";

import { PlaceholderActions, ShellPage } from "@/components/page-templates";
import { ContactSummaryCards, TablePlaceholder } from "@/components/placeholders";
import { getContactsData } from "@/lib/platform-data";
import { deleteContact } from "@/lib/admin-crud";

export default async function ContactsPage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string }>; 
}) {
  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const contacts = await getContactsData();
  const error = params.error;
  const infoMessage = error === "contact_not_found"
    ? "Contact tidak ditemukan."
    : error === "contact_has_conversations"
      ? "Contact tidak bisa dihapus karena sudah punya riwayat percakapan."
      : error === "invalid_channel"
        ? "Channel tidak valid."
        : null;

  return (
    <ShellPage
      shell="admin"
      title="Contacts"
      description="Daftar contact, filter, import/export, dan akses ke detail screen."
      actions={<PlaceholderActions primaryHref="/contacts/new" primaryLabel="Add contact" secondaryHref="/contacts/import" secondaryLabel="Import CSV" />}
    >
      <ContactSummaryCards contacts={contacts} />
      {infoMessage ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{infoMessage}</p> : null}
      <TablePlaceholder
        title="Contact list"
        columns={["Name", "Phone", "Tags", "Last Interaction", "Opt-in", "Actions"]}
        rows={contacts.map((contact) => [
          contact.fullName,
          contact.phone,
          contact.tags.join(", "),
          contact.lastInteraction,
          contact.optInStatus,
          <div key={contact.id} className="flex flex-wrap gap-2">
            <Link href={`/contacts/${contact.id}`} className="text-brand hover:underline">
              Detail
            </Link>
            <Link href={`/contacts/${contact.id}/edit`} className="text-brand hover:underline">
              Edit
            </Link>
            <form action={deleteContact} className="inline">
              <input type="hidden" name="contactId" value={contact.id} />
            <button type="submit" className="text-danger hover:underline">
              Hapus
            </button>
            </form>
          </div>
        ])}
      />
    </ShellPage>
  );
}
