"use client";

import { useState, useTransition } from "react";
import Link from "next/link";
import { motion } from "motion/react";
import { Trash2, Save, ExternalLink, Bookmark } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Progress } from "@/components/ui/progress";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ScoreRing } from "@/components/score-ring";
import { DemoBadge } from "@/components/dashboard/demo-badge";
import { useLanguage } from "@/lib/i18n/context";
import { unsaveProductAction, updateSavedProductNotesAction } from "@/actions/product-actions";
import { STAGGER_CONTAINER, STAGGER_ITEM } from "@/components/dashboard/motion-variants";
import type { SavedProductView } from "@/lib/product-data/view-models";

function formatDate(date: Date, locale: "en" | "es"): string {
  return new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  }).format(date);
}

function SavedProductRow({ saved }: { saved: SavedProductView }) {
  const { t, locale } = useLanguage();
  const s = t.savedProducts;
  const [notes, setNotes] = useState(saved.notes ?? "");
  const [removed, setRemoved] = useState(false);
  const [isPending, startTransition] = useTransition();

  function handleRemove() {
    setRemoved(true);
    startTransition(async () => {
      const result = await unsaveProductAction(saved.product.id, locale);
      if (!result.success) {
        setRemoved(false);
        toast.error(result.error);
      }
    });
  }

  function handleSaveNotes() {
    startTransition(async () => {
      const result = await updateSavedProductNotesAction(saved.product.id, notes, locale);
      if (!result.success) toast.error(result.error);
      else toast.success(s.saveNotes);
    });
  }

  if (removed) return null;

  return (
    <motion.div variants={STAGGER_ITEM} className="flex flex-col gap-4 border-b px-5 py-5 last:border-b-0 sm:flex-row sm:items-start">
      {saved.product.score ? (
        <ScoreRing value={saved.product.score.opportunityScore} size={56} strokeWidth={5} />
      ) : null}
      <div className="flex min-w-0 flex-1 flex-col gap-2">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <Link
            href={`/dashboard/products/${saved.product.id}`}
            className="truncate text-sm font-semibold text-foreground hover:text-primary"
          >
            {saved.product.canonicalName}
          </Link>
          <span className="text-xs text-muted-foreground">
            {s.savedOn.replace("{date}", formatDate(saved.createdAt, locale))}
          </span>
        </div>
        <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
          <span>{saved.product.category}</span>
          {saved.product.isDemo && <DemoBadge />}
        </div>
        <div className="flex flex-col gap-1.5">
          <label className="text-xs text-muted-foreground" htmlFor={`notes-${saved.id}`}>
            {s.notes}
          </label>
          <Textarea
            id={`notes-${saved.id}`}
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder={s.notesPlaceholder}
            rows={2}
          />
          <div className="flex justify-end">
            <Button size="sm" variant="outline" onClick={handleSaveNotes} disabled={isPending}>
              <Save className="size-3.5" />
              {s.saveNotes}
            </Button>
          </div>
        </div>
      </div>
      <div className="flex shrink-0 flex-row gap-2 sm:flex-col">
        <Button asChild variant="ghost" size="sm">
          <Link href={`/dashboard/products/${saved.product.id}`}>
            <ExternalLink className="size-3.5" />
            {s.openProduct}
          </Link>
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={handleRemove}
          disabled={isPending}
          className="text-destructive hover:text-destructive"
        >
          <Trash2 className="size-4" />
          {s.remove}
        </Button>
      </div>
    </motion.div>
  );
}

export function SavedProductsPageContent({
  savedProducts,
  used,
  limit,
  loadError = false,
}: {
  savedProducts: SavedProductView[];
  used: number;
  limit: number;
  loadError?: boolean;
}) {
  const { t } = useLanguage();
  const s = t.savedProducts;
  const percent = limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0;

  return (
    <div className="flex w-full max-w-[1500px] flex-col gap-4 pb-8">
      <div className="pt-0.5">
        <h1 className="text-[26px] font-semibold tracking-tight text-foreground sm:text-[28px]">{s.title}</h1>
        <p className="mt-1 max-w-2xl text-sm text-muted-foreground">{s.description}</p>
      </div>

      {loadError ? (
        <Card className="flex min-h-40 items-center justify-center rounded-2xl p-8 text-center">
          <p className="text-sm text-muted-foreground">{t.errors.generic}</p>
        </Card>
      ) : (
        <>
          <Card className="rounded-2xl p-4">
            <div className="flex items-baseline justify-between text-xs text-muted-foreground">
              <span>{s.limitUsage.replace("{used}", String(used)).replace("{limit}", String(limit))}</span>
              {used >= limit && <span className="font-semibold text-destructive">{s.limitReached}</span>}
            </div>
            <Progress value={percent} className="mt-2 h-1.5" />
          </Card>

          <Card className="gap-0 overflow-hidden rounded-2xl py-0">
            <div className="flex items-center gap-3 border-b px-5 py-4">
              <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
                <Bookmark className="size-4" aria-hidden="true" />
              </span>
              <div className="flex items-center gap-2">
                <p className="text-[15px] font-bold text-foreground">{s.title}</p>
                <Badge variant="outline" className="font-normal text-muted-foreground">
                  {savedProducts.length}
                </Badge>
              </div>
            </div>

            {savedProducts.length === 0 ? (
              <div className="flex min-h-40 items-center justify-center p-8 text-center">
                <p className="text-sm text-muted-foreground">{s.empty}</p>
              </div>
            ) : (
              <motion.div initial="hidden" whileInView="visible" viewport={{ once: true, amount: 0.1 }} variants={STAGGER_CONTAINER}>
                {savedProducts.map((saved) => (
                  <SavedProductRow key={saved.id} saved={saved} />
                ))}
              </motion.div>
            )}
          </Card>
        </>
      )}
    </div>
  );
}
