import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { getProject, listProcessedTickets } from "../../lib/api";
import {
  buildTicketResourceLink,
  DEFAULT_TICKET_RESOURCE_CONFIG,
  fetchTicketResourceConfig,
  type TicketResourceConfig,
} from "../../lib/ticketResource";
import type { ProcessedTicket, Project } from "../../lib/types";
import TicketStatusBadge from "../ui/TicketStatusBadge";
import {
  cardContentClass,
  pageClass,
  pageTitleClass,
  pillClass,
} from "../ui/primitives";

export default function TicketList() {
  const { projectId } = useParams();
  const [project, setProject] = useState<Project | null>(null);
  const [tickets, setTickets] = useState<ProcessedTicket[]>([]);
  const [resourceConfig, setResourceConfig] = useState<TicketResourceConfig>(
    DEFAULT_TICKET_RESOURCE_CONFIG
  );
  const [filter, setFilter] = useState<string>("all");

  useEffect(() => {
    if (!projectId) return;
    let cancelled = false;
    Promise.all([getProject(projectId), listProcessedTickets(projectId)])
      .then(([proj, tkts]) => {
        if (cancelled) return;
        setProject(proj);
        setTickets(tkts);
      })
      .catch((error: unknown) => {
        console.error("Failed to load ticket list", error);
      });

    void fetchTicketResourceConfig(projectId)
      .then((config) => {
        if (!cancelled) {
          setResourceConfig(config);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setResourceConfig(DEFAULT_TICKET_RESOURCE_CONFIG);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [projectId]);

  const filtered = filter === "all" ? tickets : tickets.filter((t) => t.status === filter);

  return (
    <div className={pageClass}>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <Link to={`/projects/${projectId}`} className="text-sm text-blue-600 hover:underline">
            {project?.name}
          </Link>
          <h2 className={pageTitleClass}>Processed Tickets</h2>
        </div>
      </div>

      <div className="mb-4 flex gap-2">
        {["all", "Pending", "Analyzing", "Developing", "Done", "Error"].map((s) => (
          <button
            key={s}
            onClick={() => setFilter(s)}
            className={pillClass(filter === s)}
          >
            {s === "all" ? "All" : s}
            {s !== "all" && (
              <span className="ml-1 text-xs opacity-60">
                ({tickets.filter((t) => t.status === s).length})
              </span>
            )}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="py-8 text-center text-sm text-gray-400">No tickets found.</div>
      ) : (
        <div className="space-y-2">
          {filtered.map((ticket) => {
            const resourceLink = buildTicketResourceLink(ticket, resourceConfig);
            return (
              <div key={ticket.id} className={`transition-colors hover:border-blue-300 ${cardContentClass}`}>
                <div className="flex items-center justify-between gap-4">
                  <Link to={`/tickets/${ticket.id}`} className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-mono text-xs text-gray-400">#{ticket.artifact_id}</span>
                      <span className="rounded bg-gray-100 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gray-600">
                        {ticket.source}
                      </span>
                      <span className="truncate text-sm font-medium">{ticket.artifact_title}</span>
                    </div>
                    <div className="mt-1 text-xs text-gray-400">
                      {new Date(ticket.detected_at).toLocaleString()}
                      {ticket.processed_at && (
                        <span className="ml-2">
                          Processed: {new Date(ticket.processed_at).toLocaleString()}
                        </span>
                      )}
                    </div>
                  </Link>
                  <div className="flex shrink-0 items-center gap-3">
                    {resourceLink && (
                      <a
                        href={resourceLink.href}
                        target="_blank"
                        rel="noreferrer"
                        className="text-xs text-blue-600 hover:underline"
                        title={resourceLink.label}
                      >
                        Ressource
                      </a>
                    )}
                    <TicketStatusBadge status={ticket.status} className="shrink-0" />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
