import Link from "next/link"
import { fetchQuery } from "convex/nextjs"
import { ContactRound, Search } from "lucide-react"
import { api } from "@/convex/_generated/api"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"

type PageProps = {
  searchParams: Promise<{
    search?: string
    page?: string
  }>
}

function formatTimestamp(value?: number) {
  if (!value) {
    return "—"
  }

  return new Date(value).toLocaleString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  })
}

function getSyncMessage(sync: any) {
  if (!sync.ghlConfigured) {
    return "Connect GHL to load contacts and conversations."
  }
  if (sync.stages.contacts.status === "running") {
    return "Contacts are syncing now."
  }
  if (sync.stages.contacts.error) {
    return "Contacts could not be loaded from GHL yet."
  }
  if (!sync.latestSyncAt) {
    return "No contacts yet."
  }
  return "Your contact list stays up to date from forms, calls, and GHL."
}

export default async function AdminContactsPage({ searchParams }: PageProps) {
  const params = await searchParams
  const page = Math.max(1, Number.parseInt(params.page || "1", 10) || 1)
  const search = params.search?.trim() || undefined

  const data = await fetchQuery(api.crm.listAdminContacts, {
    search,
    page,
    limit: 25,
  })

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="space-y-8">
        <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
          <div>
            <h1 className="text-4xl font-bold tracking-tight text-balance">
              Contacts
            </h1>
            <p className="mt-2 text-muted-foreground">
              All customer contacts in one place.
            </p>
          </div>
          <Link href="/admin">
            <Button variant="outline">Back to Admin</Button>
          </Link>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Sync Status</CardTitle>
            <CardDescription>{getSyncMessage(data.sync)}</CardDescription>
          </CardHeader>
          <CardContent className="flex flex-wrap gap-3 text-sm text-muted-foreground">
            <Badge variant="outline">{data.sync.overallStatus}</Badge>
            <span>
              Last sync: {formatTimestamp(data.sync.latestSyncAt || undefined)}
            </span>
            {!data.sync.ghlConfigured ? (
              <span>GHL is not connected.</span>
            ) : null}
            {data.sync.stages.contacts.error ? (
              <span>{data.sync.stages.contacts.error}</span>
            ) : null}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ContactRound className="h-5 w-5" />
              Contact Directory
            </CardTitle>
            <CardDescription>
              Search by name, email, phone, company, or tag.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <form className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]">
              <div className="relative">
                <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  name="search"
                  defaultValue={search || ""}
                  placeholder="Search contacts"
                  className="pl-9"
                />
              </div>
              <Button type="submit">Filter</Button>
            </form>

            <div className="overflow-x-auto">
              <table className="w-full min-w-[980px] text-sm">
                <thead>
                  <tr className="border-b text-left text-muted-foreground">
                    <th className="py-3 pr-4 font-medium">Contact</th>
                    <th className="py-3 pr-4 font-medium">Company</th>
                    <th className="py-3 pr-4 font-medium">Status</th>
                    <th className="py-3 pr-4 font-medium">Conversations</th>
                    <th className="py-3 pr-4 font-medium">Leads</th>
                    <th className="py-3 pr-4 font-medium">Last Activity</th>
                    <th className="py-3 font-medium">Open</th>
                  </tr>
                </thead>
                <tbody>
                  {data.items.length === 0 ? (
                    <tr>
                      <td
                        colSpan={7}
                        className="py-8 text-center text-muted-foreground"
                      >
                        {search
                          ? "No contacts matched this search."
                          : getSyncMessage(data.sync)}
                      </td>
                    </tr>
                  ) : (
                    data.items.map((contact: any) => (
                      <tr
                        key={contact.id}
                        className="border-b align-top last:border-b-0"
                      >
                        <td className="py-3 pr-4">
                          <div className="font-medium">{contact.displayName}</div>
                          {contact.email ? (
                            <div className="text-xs text-muted-foreground">
                              {contact.email}
                            </div>
                          ) : null}
                          {contact.phone ? (
                            <div className="text-xs text-muted-foreground">
                              {contact.phone}
                            </div>
                          ) : null}
                        </td>
                        <td className="py-3 pr-4">
                          {contact.company || "—"}
                        </td>
                        <td className="py-3 pr-4">
                          <Badge variant="secondary">{contact.status}</Badge>
                        </td>
                        <td className="py-3 pr-4">{contact.conversationCount}</td>
                        <td className="py-3 pr-4">{contact.leadCount}</td>
                        <td className="py-3 pr-4">
                          {formatTimestamp(contact.lastActivityAt)}
                        </td>
                        <td className="py-3">
                          <Link href={`/admin/contacts/${contact.id}`}>
                            <Button size="sm" variant="outline">
                              View
                            </Button>
                          </Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

export const metadata = {
  title: "Contacts | Admin",
  description: "View Rocky customer contacts",
}
