import { createFileRoute, Link } from '@tanstack/react-router'
import { CircleAlert, Coins, MessageSquareText, Send } from 'lucide-react'
import { z } from 'zod'
import { Skeleton } from '@/components/ui/skeleton'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import {
  CustomerCell,
  EmptyState,
  Panel,
  PageIntro,
  StatusBadge,
  SummaryStrip,
  dateFormat,
  filterBarClass,
  filterClass,
  timeAgo,
} from '@/components/admin/AdminUi'
import { getAdminCampaigns } from '@/lib/admin.functions'
import { voiceLabel } from '@/lib/voice'

const statusSchema = z.enum(['all', 'sent', 'partial', 'failed', 'sending', 'scheduled', 'cancelled'])
type Status = z.infer<typeof statusSchema>
const channelSchema = z.enum(['sms', 'voice'])
type Channel = z.infer<typeof channelSchema>

export const Route = createFileRoute('/admin/messages')({
  validateSearch: z.object({ status: statusSchema.catch('all'), channel: channelSchema.optional().catch(undefined) }),
  loaderDeps: ({ search }) => ({ status: search.status, channel: search.channel }),
  loader: ({ deps }) => getAdminCampaigns({ data: { status: deps.status, channel: deps.channel ?? 'all' } }),
  head: () => ({ meta: [{ title: 'Admin · Messages — AkotoCreative SMS' }] }),
  pendingComponent: () => <Skeleton className="h-96 rounded-2xl" />,
  component: MessagesPage,
})

const FILTERS: { value: Status; label: string }[] = [
  { value: 'all', label: 'All' },
  { value: 'sent', label: 'Sent' },
  { value: 'partial', label: 'Partly sent' },
  { value: 'failed', label: 'Failed' },
  { value: 'sending', label: 'Sending' },
  { value: 'scheduled', label: 'Scheduled' },
  { value: 'cancelled', label: 'Cancelled' },
]

const CHANNELS: { value: Channel | undefined; label: string }[] = [
  { value: undefined, label: 'SMS and voice' },
  { value: 'sms', label: 'SMS' },
  { value: 'voice', label: 'Voice SMS' },
]

function MessagesPage() {
  const { status, channel } = Route.useSearch()
  const campaigns = Route.useLoaderData()

  return (
    <div className="grid gap-6">
      <PageIntro eyebrow="Traffic" title="Messages">
        Every bulk SMS and voice send across all customers, newest first. Credits shown are what was charged after refunds for
        failed batches. Moolre’s reason is shown under any failed send.
      </PageIntro>

      <SummaryStrip
        items={[
          { label: 'Sends shown', value: campaigns.length.toLocaleString(), icon: MessageSquareText },
          {
            label: 'Numbers reached',
            value: campaigns.reduce((sum, c) => sum + c.recipientCount, 0).toLocaleString(),
            icon: Send,
          },
          {
            label: 'Credits charged',
            value: campaigns.reduce((sum, c) => sum + c.creditsUsed, 0).toLocaleString(),
            icon: Coins,
            tone: 'gold',
          },
          {
            label: 'Failed',
            value: campaigns.filter((c) => c.status === 'failed').length.toLocaleString(),
            icon: CircleAlert,
            tone: 'red',
          },
        ]}
      />

      <nav aria-label="Message type" className={filterBarClass}>
        {CHANNELS.map((f) => (
          <Link
            key={f.label}
            to="/admin/messages"
            search={{ status, channel: f.value }}
            className={filterClass(f.value === channel)}
            aria-current={f.value === channel ? 'page' : undefined}
          >
            {f.label}
          </Link>
        ))}
      </nav>

      <nav aria-label="Message status" className={filterBarClass}>
        {FILTERS.map((f) => (
          <Link
            key={f.value}
            to="/admin/messages"
            search={{ status: f.value, channel }}
            className={filterClass(f.value === status)}
            aria-current={f.value === status ? 'page' : undefined}
          >
            {f.label}
          </Link>
        ))}
      </nav>

      {campaigns.length === 0 ? (
        <EmptyState icon={MessageSquareText}>{status === 'all' && !channel ? 'No messages sent yet.' : 'No messages match these filters.'}</EmptyState>
      ) : (
        <Panel>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Customer</TableHead>
                <TableHead>Sender</TableHead>
                <TableHead>Message</TableHead>
                <TableHead className="text-right">Recipients</TableHead>
                <TableHead className="text-right">Credits</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {campaigns.map((c) => (
                <TableRow key={c.id}>
                  <TableCell className="whitespace-nowrap">
                    {dateFormat.format(new Date(c.createdAt))}
                    <p className="text-xs text-muted-foreground">{timeAgo(c.createdAt)}</p>
                  </TableCell>
                  <TableCell>
                    <CustomerCell email={c.email} />
                  </TableCell>
                  <TableCell>
                    <span className="rounded-md bg-secondary px-2 py-1 font-mono text-xs font-semibold">{c.senderId}</span>
                    {c.channel === 'voice' && (
                      <p className="mt-1 text-xs text-muted-foreground">Voice · {voiceLabel(c.voice)}</p>
                    )}
                  </TableCell>
                  <TableCell title={c.message}>
                    <p className="max-w-xs truncate rounded-xl rounded-bl-sm bg-muted px-3 py-1.5 text-sm">{c.message}</p>
                  </TableCell>
                  <TableCell className="text-right tabular-nums">
                    {c.recipientCount.toLocaleString()}
                    {c.channel === 'sms' && c.segments > 1 && <p className="text-xs text-muted-foreground">{c.segments} parts each</p>}
                  </TableCell>
                  <TableCell className="text-right tabular-nums">{c.creditsUsed.toLocaleString()}</TableCell>
                  <TableCell>
                    <StatusBadge status={c.status} title={c.providerResponse ?? undefined} />
                    {c.providerResponse && c.status !== 'sent' && (
                      <p className="mt-1 max-w-48 truncate text-xs text-muted-foreground" title={c.providerResponse}>
                        {c.providerResponse}
                      </p>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Panel>
      )}
    </div>
  )
}
