"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import {
  FileText,
  Clock,
  CheckCircle2,
  PlusCircle,
  AlertCircle,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { useAuthStore } from "@/lib/store/auth-store";
import { useTranslation } from "@/lib/hooks/use-translation";
import { paperApi } from "@/lib/api/client";
import type { Paper, PageResponse } from "@/types";

/* ───── Status badge config ───── */

const statusColors: Record<string, string> = {
  DRAFT: "bg-gray-100 text-gray-700",
  PAYMENT_PENDING: "bg-amber-100 text-amber-800",
  SUBMITTED: "bg-blue-100 text-blue-700",
  SCREENING: "bg-blue-100 text-blue-700",
  PENDING_ASSIGNMENT: "bg-amber-100 text-amber-700",
  UNDER_REVIEW: "bg-yellow-100 text-yellow-700",
  REVISION_REQUESTED: "bg-orange-100 text-orange-700",
  REVISION_SUBMITTED: "bg-orange-100 text-orange-700",
  REVIEW_COMPLETE: "bg-teal-100 text-teal-700",
  ACCEPTED: "bg-green-100 text-green-700",
  REJECTED: "bg-red-100 text-red-700",
  PUBLISHED: "bg-green-100 text-green-800",
  WITHDRAWN: "bg-gray-100 text-gray-600",
};

function StatusBadge({ status, cms }: { status: string; cms: (key: string, fallback?: string) => string }) {
  const color = statusColors[status] ?? "bg-gray-100 text-gray-700";
  return (
    <span className={cn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium", color)}>
      {cms(`STATUS_LABELS.paper.${status.toLowerCase()}`, status)}
    </span>
  );
}

/* ───── Page ───── */

export default function AuthorDashboard() {
  const user = useAuthStore((s) => s.user);
  const { t: cms, language } = useTranslation(["AUTHOR", "STATUS_LABELS", "COMMON"]);

  const { data, isLoading, error } = useQuery<PageResponse<Paper>>({
    queryKey: ["author-papers"],
    queryFn: async () => {
      const res = await paperApi.list();
      return res.data;
    },
  });

  const papers = data?.content ?? [];
  const totalPapers = papers.length;
  const underReview = papers.filter(
    (p) => p.status === "UNDER_REVIEW" || p.status === "SCREENING" || p.status === "PENDING_ASSIGNMENT"
  ).length;
  const published = papers.filter((p) => p.status === "PUBLISHED").length;

  const displayName = language === "hi" ? user?.nameHi : user?.nameEn;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <p className="text-gray-500 text-lg">{cms("COMMON.labels.loading", "Loading...")}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <AlertCircle className="mx-auto h-10 w-10 text-red-400 mb-2" />
          <p className="text-red-600">{cms("COMMON.labels.error_loading", "Error loading data")}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Welcome */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            {cms("AUTHOR.author_header.greeting", "Hello")}, {displayName ?? "लेखक"} !
          </h1>
          <p className="text-gray-500 text-sm mt-1">{cms("AUTHOR.author_header.subtitle", "Author Dashboard")}</p>
        </div>
        <Link
          href="/submit"
          className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition"
        >
          <PlusCircle className="h-4 w-4" />
          {cms("AUTHOR.author_header.submit_new", "Submit New Paper")}
        </Link>
      </div>

      {/* Stats cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
        {[
          { label: cms("AUTHOR.author_stats.total_papers", "Total Papers"), value: totalPapers, icon: FileText, color: "text-indigo-600 bg-indigo-50" },
          { label: cms("AUTHOR.author_stats.under_review", "Under Review"), value: underReview, icon: Clock, color: "text-yellow-600 bg-yellow-50" },
          { label: cms("AUTHOR.author_stats.published", "Published"), value: published, icon: CheckCircle2, color: "text-green-600 bg-green-50" },
        ].map((stat) => (
          <div key={stat.label} className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm">
            <div className="flex items-center gap-3">
              <div className={cn("rounded-lg p-2.5", stat.color)}>
                <stat.icon className="h-5 w-5" />
              </div>
              <div>
                <p className="text-sm text-gray-500">{stat.label}</p>
                <p className="text-2xl font-bold text-gray-900">{stat.value}</p>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Papers table */}
      <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
        <div className="px-5 py-4 border-b border-gray-100">
          <h2 className="text-lg font-semibold text-gray-900">
            {cms("AUTHOR.author_table.table_title", "My Papers")}
          </h2>
        </div>

        {papers.length === 0 ? (
          <div className="px-5 py-12 text-center text-gray-500">
            <FileText className="mx-auto h-10 w-10 text-gray-300 mb-3" />
            <p>{cms("AUTHOR.author_table.no_papers", "No papers found")}</p>
            <Link href="/submit" className="text-indigo-600 hover:underline text-sm mt-2 inline-block">
              {cms("AUTHOR.author_table.submit_first", "Submit your first paper")}
            </Link>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 text-left">
                <tr>
                  <th className="px-5 py-3 font-medium text-gray-500">{cms("AUTHOR.author_table.col_title", "Title")}</th>
                  <th className="px-5 py-3 font-medium text-gray-500">{cms("AUTHOR.author_table.col_status", "Status")}</th>
                  <th className="px-5 py-3 font-medium text-gray-500">{cms("AUTHOR.author_table.col_submitted", "Submitted")}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {papers.map((paper) => (
                  <tr key={paper.id} className="hover:bg-gray-50 transition">
                    <td className="px-5 py-4">
                      <Link
                        href={`/papers/${paper.id}`}
                        className="font-medium text-gray-900 hover:text-indigo-600"
                      >
                        {language === "hi" && paper.titleHi ? paper.titleHi : paper.titleEn}
                      </Link>
                      {paper.referenceNo && (
                        <p className="text-xs text-gray-400 mt-0.5">{paper.referenceNo}</p>
                      )}
                    </td>
                    <td className="px-5 py-4">
                      <StatusBadge status={paper.status} cms={cms} />
                    </td>
                    <td className="px-5 py-4 text-gray-500">
                      {paper.submittedAt
                        ? new Date(paper.submittedAt).toLocaleDateString("en-IN")
                        : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
