'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Flame, Info } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import {
  fetchPqlBreakdown,
  fetchPqlLeads,
} from '@/network/apis/dashboard/marketing-analytics/marketing-analytics.apis';
import { PqlTier } from '@/network/apis/dashboard/marketing-analytics/type';
import { ROLE_LABELS, roleBadgeClass } from '../labels';

const ANY = '__any__';

const TIER_LABELS: Record<PqlTier, string> = {
  pql: 'Qualified',
  active: 'Active',
  explorer: 'Explorer',
};

const tierClass = (tier: PqlTier) => {
  switch (tier) {
    case 'pql':
      return 'bg-red-50 text-red-700 border-red-200 dark:bg-red-950/30 dark:text-red-400 dark:border-red-800';
    case 'active':
      return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/30 dark:text-amber-400 dark:border-amber-800';
    default:
      return 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-zinc-900 dark:text-zinc-400 dark:border-zinc-700';
  }
};

const when = (iso: string | null, pattern = 'd MMM yyyy') => {
  if (!iso) return '—';
  const d = new Date(iso);
  return isNaN(d.getTime()) ? '—' : format(d, pattern);
};

/**
 * Product-Qualified Leads — who is warm enough for sales to call.
 *
 * The score comes from the nightly job, over a rolling window, and each
 * behaviour counts once however many times it happened: the question is "did
 * they show this signal", not "how often". The breakdown sheet exists because
 * a score nobody can explain is a score nobody acts on.
 */
export function PqlLeads() {
  const [tier, setTier] = useState<string>(ANY);
  const [page, setPage] = useState(1);
  const [openUserId, setOpenUserId] = useState<number | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['analytics', 'pql', tier, page],
    queryFn: () => fetchPqlLeads(tier === ANY ? undefined : tier, page),
  });

  const breakdown = useQuery({
    queryKey: ['analytics', 'pql-breakdown', openUserId],
    queryFn: () => fetchPqlBreakdown(openUserId as number),
    enabled: !!openUserId,
  });

  const summary = data?.summary;
  const users = data?.users ?? [];
  const pagination = data?.pagination;

  const cards = [
    { label: 'Qualified', value: summary?.pql, color: 'text-red-600' },
    { label: 'Active', value: summary?.active, color: 'text-amber-600' },
    { label: 'Explorers', value: summary?.explorer, color: 'text-zinc-600' },
  ];

  return (
    <>
      <Card>
        <CardHeader className="pb-3">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
              <CardTitle className="text-base font-semibold flex items-center gap-2">
                <Flame className="h-4 w-4 text-red-500" />
                Qualified leads
              </CardTitle>
              {summary && (
                <p className="text-xs text-muted-foreground mt-1">
                  {summary.threshold}+ points over the last {summary.window_days} days
                  {summary.last_scored_at
                    ? ` · last scored ${when(summary.last_scored_at, 'd MMM, HH:mm')}`
                    : ' · not scored yet — the nightly job has not run'}
                </p>
              )}
            </div>
            <Select
              value={tier}
              onValueChange={(v) => {
                setTier(v);
                setPage(1);
              }}
            >
              <SelectTrigger className="h-9 w-[150px]">
                <SelectValue placeholder="Tier" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={ANY}>All with a score</SelectItem>
                <SelectItem value="pql">Qualified</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="explorer">Explorer</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardHeader>
        <CardContent className="pt-0 space-y-4">
          <div className="grid grid-cols-3 gap-3">
            {cards.map((c) => (
              <div key={c.label} className="rounded-lg border p-3">
                <p className="text-xs text-muted-foreground">{c.label}</p>
                <p className={`text-lg font-bold mt-0.5 ${c.color}`}>
                  {(c.value ?? 0).toLocaleString()}
                </p>
              </div>
            ))}
          </div>

          {isLoading ? (
            <div className="flex justify-center py-10">
              <Spinner className="h-6 w-6" />
            </div>
          ) : users.length === 0 ? (
            <p className="text-sm text-muted-foreground py-10 text-center">
              Nobody has scored yet. Scores are computed nightly from recorded
              activity, so this fills in once the job has run over real usage.
            </p>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Person</TableHead>
                    <TableHead>Role</TableHead>
                    <TableHead>Score</TableHead>
                    <TableHead>Tier</TableHead>
                    <TableHead>Source</TableHead>
                    <TableHead>Aha</TableHead>
                    <TableHead>Joined</TableHead>
                    <TableHead className="w-[50px]"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {users.map((u) => (
                    <TableRow key={u.id}>
                      <TableCell>
                        <p className="text-sm font-medium">{u.name ?? '—'}</p>
                        <p className="text-xs text-muted-foreground">{u.email}</p>
                      </TableCell>
                      <TableCell>
                        <span
                          className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium border ${roleBadgeClass(u.role)}`}
                        >
                          {ROLE_LABELS[u.role]}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm font-bold tabular-nums">
                          {u.pql_score}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span
                          className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium border ${tierClass(u.pql_tier)}`}
                        >
                          {TIER_LABELS[u.pql_tier]}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-xs">
                          {u.signup_source ?? '—'}
                          {u.signup_medium ? ` / ${u.signup_medium}` : ''}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-xs">
                          {u.aha_reached ? 'Yes' : 'No'}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-xs whitespace-nowrap">
                          {when(u.registered_at)}
                        </span>
                      </TableCell>
                      <TableCell>
                        <Button
                          variant="ghost"
                          size="sm"
                          mode="icon"
                          className="h-7 w-7"
                          onClick={() => setOpenUserId(u.id)}
                          title="Why this score?"
                        >
                          <Info className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {pagination && pagination.last_page > 1 && (
                <div className="flex items-center justify-between pt-2">
                  <p className="text-xs text-muted-foreground">
                    Page {pagination.current_page} of {pagination.last_page} ·{' '}
                    {pagination.total.toLocaleString()} people
                  </p>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={page <= 1}
                      onClick={() => setPage((p) => Math.max(1, p - 1))}
                    >
                      Previous
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={page >= pagination.last_page}
                      onClick={() => setPage((p) => p + 1)}
                    >
                      Next
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      <Sheet
        open={!!openUserId}
        onOpenChange={(open) => !open && setOpenUserId(null)}
      >
        <SheetContent className="w-full sm:max-w-md overflow-y-auto">
          {breakdown.isLoading || !breakdown.data ? (
            <div className="flex justify-center py-16">
              <Spinner className="h-6 w-6" />
            </div>
          ) : (
            <div className="space-y-5">
              <SheetHeader>
                <SheetTitle className="text-base">
                  Score: {breakdown.data.score}
                </SheetTitle>
                <p className="text-xs text-muted-foreground pt-1">
                  {TIER_LABELS[breakdown.data.tier]} · rolling{' '}
                  {breakdown.data.window_days} days · each behaviour counts once
                </p>
              </SheetHeader>

              <div className="space-y-2">
                {breakdown.data.matched.map((r) => (
                  <div
                    key={r.rule}
                    className={`rounded-lg border p-3 ${r.earned ? 'border-emerald-200 bg-emerald-50/40 dark:border-emerald-900 dark:bg-emerald-950/20' : ''}`}
                  >
                    <div className="flex items-center justify-between gap-3">
                      <p className="text-sm font-medium">{r.label}</p>
                      <span
                        className={`text-sm font-bold tabular-nums ${r.earned ? 'text-emerald-600' : 'text-muted-foreground'}`}
                      >
                        {r.earned ? `+${r.points}` : '0'}
                      </span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {r.observed} of {r.required} needed
                    </p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </SheetContent>
      </Sheet>
    </>
  );
}
