import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  BookOpen,
  Plus,
  Sparkles,
  Trash2,
  Calendar,
  Layers,
} from "lucide-react";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { coursePlanService } from "@/services/coursePlan.service";
import { describeApiError } from "@/lib/api-client";

/**
 * Admin list of AI-generated course plans.
 *
 * Each plan row shows name + CEFR + weeks + status, plus an "Open"
 * button that deep-links to the detail page. A prominent "Generate new"
 * CTA routes to the Smart Wizard's CoursePlanWizard.
 */
export default function AdminCoursePlans() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const [search, setSearch] = useState("");

  const { data, isLoading, isError, error } = useQuery({
    queryKey: ["course-plans", { search }],
    queryFn: () =>
      coursePlanService.list({
        page: 0,
        size: 50,
        search: search || undefined,
      }),
  });

  const removeMut = useMutation({
    mutationFn: (id: number) => coursePlanService.remove(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["course-plans"] });
      toast.success(t("coursePlan.deleted"));
    },
    onError: (err) =>
      toast.error(describeApiError(err, t("coursePlan.deleteFailed"))),
  });

  const items = data?.items ?? [];

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <BookOpen className="h-5 w-5 text-primary" />
            <h1 className="text-2xl font-semibold tracking-tight">
              {t("coursePlan.listTitle")}
            </h1>
          </div>
          <p className="text-muted-foreground max-w-2xl">
            {t("coursePlan.listSubtitle")}
          </p>
        </div>
        <Button onClick={() => navigate("/admin/smart-wizard/course-plan")}>
          <Sparkles className="mr-1 h-4 w-4" />
          {t("coursePlan.generateNew")}
        </Button>
      </div>

      <div className="max-w-sm">
        <Input
          placeholder={t("coursePlan.searchPlaceholder")}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {isLoading && (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} className="h-40 rounded-lg" />
          ))}
        </div>
      )}

      {isError && (
        <div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
          {describeApiError(error, t("coursePlan.loadFailed"))}
        </div>
      )}

      {!isLoading && !isError && items.length === 0 && (
        <Card>
          <CardContent className="flex flex-col items-center justify-center gap-3 py-12">
            <Sparkles className="h-8 w-8 text-muted-foreground" />
            <div className="text-center">
              <div className="font-medium">{t("coursePlan.emptyTitle")}</div>
              <div className="text-sm text-muted-foreground max-w-md">
                {t("coursePlan.emptySubtitle")}
              </div>
            </div>
            <Button onClick={() => navigate("/admin/smart-wizard/course-plan")}>
              <Plus className="mr-1 h-4 w-4" />
              {t("coursePlan.generateNew")}
            </Button>
          </CardContent>
        </Card>
      )}

      {!isLoading && items.length > 0 && (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {items.map((plan) => (
            <Card key={plan.id} className="flex flex-col">
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between gap-2">
                  <CardTitle className="text-base line-clamp-2">{plan.name}</CardTitle>
                  <Badge variant={plan.status === "approved" ? "default" : "outline"}>
                    {t(`coursePlan.status.${plan.status}`, plan.status)}
                  </Badge>
                </div>
                <CardDescription className="line-clamp-2">
                  {plan.description || t("coursePlan.noDescription")}
                </CardDescription>
              </CardHeader>
              <CardContent className="flex-1 flex flex-col justify-between gap-3">
                <div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Badge variant="secondary" className="text-[10px] uppercase">
                      {plan.cefr_level || "—"}
                    </Badge>
                  </span>
                  <span className="flex items-center gap-1">
                    <Calendar className="h-3.5 w-3.5" />
                    {t("coursePlan.weeksCount", { count: plan.total_weeks })}
                  </span>
                  <span className="flex items-center gap-1">
                    <Layers className="h-3.5 w-3.5" />
                    {t("coursePlan.materialsCount", { count: plan.material_count })}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <Button asChild variant="default" size="sm" className="flex-1">
                    <Link to={`/admin/course-plans/${plan.id}`}>
                      {t("coursePlan.open")}
                    </Link>
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-destructive"
                    onClick={() => {
                      if (!window.confirm(t("coursePlan.confirmDelete", { name: plan.name }))) return;
                      removeMut.mutate(plan.id);
                    }}
                    aria-label={t("coursePlan.delete")}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
