import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { CAMPAIGN_DRAFTS, CHANNELS, formatNaira } from "@/lib/campaign-data";
import { listCampaignsFn } from "@/lib/campaigns/campaigns.functions";
import type { ChannelId } from "@/lib/campaigns/types";
import { FileText, ArrowRight } from "lucide-react";

export const Route = createFileRoute("/campaigns/drafts")({
  component: DraftsPage,
});

function DraftsPage() {
  const draftsQuery = useQuery({
    queryKey: ["campaigns", "drafts"],
    queryFn: () => listCampaignsFn({ data: { status: "draft" } }),
  });
  const drafts = draftsQuery.data?.length
    ? draftsQuery.data.map((d) => ({
        id: d.id,
        name: d.name,
        updated: new Date(d.updatedAt).toLocaleDateString(),
        step: d.step,
        type: d.type,
        channels: d.channels,
        estimate: formatNaira(d.estimate.total),
      }))
    : CAMPAIGN_DRAFTS.map((d) => ({ ...d, estimate: "Mock" }));

  return (
    <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
      {drafts.map((d) => (
        <Card key={d.id} className="group hover:border-primary/40 transition-colors">
          <CardContent className="p-5 space-y-3">
            <div className="flex items-center justify-between">
              <span className="h-8 w-8 grid place-items-center rounded-md bg-muted text-muted-foreground">
                <FileText className="h-4 w-4" />
              </span>
              <Badge variant="outline" className="text-[10px]">
                Step {d.step}/6
              </Badge>
            </div>
            <div>
              <div className="font-semibold text-sm">{d.name}</div>
              <div className="text-xs text-muted-foreground">
                {d.type} · updated {d.updated} · {d.estimate}
              </div>
            </div>
            <div className="flex items-center gap-1">
              {(d.channels as ChannelId[]).map((id) => {
                const meta = CHANNELS.find((c) => c.id === id)!;
                const Icon = meta.icon;
                return (
                  <span key={id} className="h-6 w-6 grid place-items-center rounded-md bg-muted">
                    <Icon className="h-3 w-3" />
                  </span>
                );
              })}
            </div>
            <Progress value={(d.step / 6) * 100} className="h-1" />
            <Button size="sm" variant="outline" className="w-full gap-1.5" asChild>
              <Link to="/campaigns/new">
                Resume <ArrowRight className="h-3 w-3" />
              </Link>
            </Button>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
