"use client";

import { useState, useEffect, useCallback } from "react";
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { GitCompareArrows, X, Check } from "lucide-react";

const LINE_COLORS = ["#2563eb", "#dc2626", "#16a34a", "#d97706", "#7c3aed"];

interface WindowMetrics {
  label: string;
  impressions: number;
  likes: number;
  retweets: number;
  replies: number;
  clicks: number;
}

interface PostComparison {
  postId: string;
  content: string;
  publishedAt: string | null;
  windows: WindowMetrics[];
}

interface SelectablePost {
  id: string;
  content: string;
  status: string;
  publishedAt: string | null;
}

type MetricKey = "impressions" | "likes" | "retweets";

export function PostComparisonView() {
  const [open, setOpen] = useState(false);
  const [posts, setPosts] = useState<SelectablePost[]>([]);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [comparisons, setComparisons] = useState<PostComparison[]>([]);
  const [metric, setMetric] = useState<MetricKey>("impressions");
  const [loading, setLoading] = useState(false);
  const [step, setStep] = useState<"select" | "results">("select");

  // Load published posts for selection
  useEffect(() => {
    if (!open) return;
    fetch("/api/v1/posts?limit=50&status=PUBLISHED")
      .then((r) => (r.ok ? r.json() : []))
      .then((data: SelectablePost[]) => {
        const published = Array.isArray(data)
          ? data.filter((p) => p.status === "PUBLISHED")
          : [];
        setPosts(published);
      })
      .catch(() => setPosts([]));
  }, [open]);

  const togglePost = (id: string) => {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : prev.length < 5 ? [...prev, id] : prev
    );
  };

  const fetchComparison = useCallback(async () => {
    if (selectedIds.length < 1) return;
    setLoading(true);
    try {
      const res = await fetch(
        `/api/v1/analytics/compare?postIds=${selectedIds.join(",")}&windows=1h,12h,1d,7d`
      );
      if (res.ok) {
        const data = await res.json();
        const list = Array.isArray(data) ? data : data.comparisons ?? [];
        setComparisons(list);
        setStep("results");
      }
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  }, [selectedIds]);

  const handleClose = () => {
    setOpen(false);
    setStep("select");
    setSelectedIds([]);
    setComparisons([]);
  };

  // Build chart data: each window label is a point on the X axis
  const chartData = comparisons.length > 0
    ? comparisons[0].windows.map((w, i) => {
        const point: Record<string, string | number> = { window: w.label };
        comparisons.forEach((c, ci) => {
          const label = c.content.slice(0, 30) + (c.content.length > 30 ? "..." : "");
          point[label] = c.windows[i]?.[metric] ?? 0;
        });
        return point;
      })
    : [];

  const lineKeys = comparisons.map(
    (c) => c.content.slice(0, 30) + (c.content.length > 30 ? "..." : "")
  );

  const METRIC_OPTIONS: { key: MetricKey; label: string }[] = [
    { key: "impressions", label: "Impressions" },
    { key: "likes", label: "Likes" },
    { key: "retweets", label: "Shares" },
  ];

  return (
    <Dialog open={open} onOpenChange={(o) => (o ? setOpen(true) : handleClose())}>
      <Button
        variant="outline"
        size="sm"
        className="border-gray-200 text-gray-700 hover:bg-gray-50"
        onClick={() => setOpen(true)}
      >
        <GitCompareArrows className="h-4 w-4 mr-1.5" />
        Compare Posts
      </Button>
      <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {step === "select" ? "Select Posts to Compare" : "Post Performance Comparison"}
          </DialogTitle>
        </DialogHeader>

        {step === "select" && (
          <div className="space-y-3">
            <p className="text-xs text-gray-500">
              Select 2-5 published posts to compare their performance over time.
            </p>
            <div className="max-h-64 overflow-y-auto space-y-1 border border-gray-100 rounded-lg p-2">
              {posts.length === 0 ? (
                <p className="text-sm text-gray-400 text-center py-4">No published posts found</p>
              ) : (
                posts.map((post) => {
                  const selected = selectedIds.includes(post.id);
                  return (
                    <button
                      key={post.id}
                      onClick={() => togglePost(post.id)}
                      className={`w-full text-left px-3 py-2 rounded-md text-sm flex items-center gap-2 transition-colors ${
                        selected
                          ? "bg-blue-50 border border-blue-200"
                          : "hover:bg-gray-50 border border-transparent"
                      }`}
                    >
                      <span
                        className={`flex-shrink-0 w-5 h-5 rounded border flex items-center justify-center ${
                          selected ? "bg-blue-600 border-blue-600 text-white" : "border-gray-300"
                        }`}
                      >
                        {selected && <Check className="h-3 w-3" />}
                      </span>
                      <span className="truncate flex-1 text-gray-700">{post.content}</span>
                      {post.publishedAt && (
                        <span className="text-xs text-gray-400 flex-shrink-0">
                          {new Date(post.publishedAt).toLocaleDateString()}
                        </span>
                      )}
                    </button>
                  );
                })
              )}
            </div>
            <div className="flex items-center justify-between">
              <span className="text-xs text-gray-500">{selectedIds.length}/5 selected</span>
              <Button
                size="sm"
                disabled={selectedIds.length < 2 || loading}
                onClick={fetchComparison}
                className="bg-gray-900 hover:bg-gray-800 text-white"
              >
                {loading ? "Loading..." : "Compare"}
              </Button>
            </div>
          </div>
        )}

        {step === "results" && (
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setStep("select")}
                className="text-gray-500"
              >
                <X className="h-3 w-3 mr-1" />
                Back
              </Button>
              <div className="flex gap-1 ml-auto">
                {METRIC_OPTIONS.map((opt) => (
                  <Button
                    key={opt.key}
                    variant={metric === opt.key ? "default" : "outline"}
                    size="sm"
                    className={
                      metric === opt.key
                        ? "bg-gray-900 hover:bg-gray-800 text-white"
                        : "border-gray-200 text-gray-700 hover:bg-gray-50"
                    }
                    onClick={() => setMetric(opt.key)}
                  >
                    {opt.label}
                  </Button>
                ))}
              </div>
            </div>

            {/* Line chart */}
            <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-700">
                  {METRIC_OPTIONS.find((o) => o.key === metric)?.label} by Time Window
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div role="img" aria-label={`Post comparison - line chart showing ${METRIC_OPTIONS.find((o) => o.key === metric)?.label ?? metric} by time window`}>
                <ResponsiveContainer width="100%" height={280}>
                  <LineChart data={chartData}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
                    <XAxis dataKey="window" tick={{ fontSize: 12, fill: "#6b7280" }} />
                    <YAxis tick={{ fontSize: 11, fill: "#9ca3af" }} />
                    <Tooltip />
                    <Legend />
                    {lineKeys.map((key, i) => (
                      <Line
                        key={key}
                        type="monotone"
                        dataKey={key}
                        stroke={LINE_COLORS[i % LINE_COLORS.length]}
                        strokeWidth={2}
                        dot={{ r: 4 }}
                      />
                    ))}
                  </LineChart>
                </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>

            {/* Table view */}
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b">
                    <th className="pb-2 pr-3 text-left font-medium text-gray-500">Post</th>
                    {comparisons[0]?.windows.map((w) => (
                      <th key={w.label} className="pb-2 px-3 text-right font-medium text-gray-500">
                        {w.label}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {comparisons.map((c, ci) => (
                    <tr key={c.postId} className="border-b last:border-0">
                      <td className="py-2 pr-3 max-w-[200px]">
                        <div className="flex items-center gap-2">
                          <span
                            className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                            style={{ backgroundColor: LINE_COLORS[ci % LINE_COLORS.length] }}
                          />
                          <span className="truncate text-gray-700">{c.content}</span>
                        </div>
                      </td>
                      {c.windows.map((w) => (
                        <td key={w.label} className="py-2 px-3 text-right text-gray-600 tabular-nums">
                          {w[metric].toLocaleString()}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
