import { permissions } from "@mrp/shared";
import type { ProjectPriority, ProjectStatus, ProjectSummaryDto } from "@mrp/shared/dist/projects/types.js";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { projectPriorityFilters, projectStatusFilters } from "./config";
import { ProjectPriorityBadge } from "./ProjectPriorityBadge";
import { ProjectStatusBadge } from "./ProjectStatusBadge";

export function ProjectListPage() {
  const { token, user } = useAuth();
  const [projects, setProjects] = useState<ProjectSummaryDto[]>([]);
  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | ProjectStatus>("ALL");
  const [priorityFilter, setPriorityFilter] = useState<"ALL" | ProjectPriority>("ALL");
  const [status, setStatus] = useState("Load projects, linked customer work, and program ownership.");

  const canManage = user?.permissions.includes(permissions.projectsWrite) ?? false;

  useEffect(() => {
    if (!token) {
      return;
    }

    setStatus("Loading projects...");
    api
      .getProjects(token, {
        q: query || undefined,
        status: statusFilter === "ALL" ? undefined : statusFilter,
        priority: priorityFilter === "ALL" ? undefined : priorityFilter,
      })
      .then((nextProjects) => {
        setProjects(nextProjects);
        setStatus(nextProjects.length === 0 ? "No projects matched the current filters." : `${nextProjects.length} project(s) loaded.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load projects.";
        setStatus(message);
      });
  }, [priorityFilter, query, statusFilter, token]);

  return (
    <section className="space-y-4">
      <div className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Projects</p>
            <h3 className="mt-2 text-xl font-bold text-text">Program records</h3>
            <p className="mt-2 max-w-3xl text-sm text-muted">Track long-running customer programs across commercial commitments, shipment deliverables, ownership, and due dates.</p>
          </div>
          {canManage ? (
            <Link to="/projects/new" className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">
              New project
            </Link>
          ) : null}
        </div>
      </div>
      <section className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_0.45fr_0.45fr]">
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Search</span>
            <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Project number, name, customer" className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand" />
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Status</span>
            <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as "ALL" | ProjectStatus)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              {projectStatusFilters.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-semibold text-text">Priority</span>
            <select value={priorityFilter} onChange={(event) => setPriorityFilter(event.target.value as "ALL" | ProjectPriority)} className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand">
              {projectPriorityFilters.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
          </label>
        </div>
        <div className="mt-5 rounded-2xl border border-line/70 bg-page/70 px-2 py-2 text-sm text-muted">{status}</div>
        {projects.length === 0 ? (
          <div className="mt-5 rounded-[18px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">No projects are available for the current filters.</div>
        ) : (
          <div className="mt-5 overflow-hidden rounded-2xl border border-line/70">
            <table className="min-w-full divide-y divide-line/70 text-sm">
              <thead className="bg-page/80 text-left text-muted">
                <tr>
                  <th className="px-2 py-2">Project</th>
                  <th className="px-2 py-2">Customer</th>
                  <th className="px-2 py-2">Owner</th>
                  <th className="px-2 py-2">Status</th>
                  <th className="px-2 py-2">Priority</th>
                  <th className="px-2 py-2">Due</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line/70 bg-surface">
                {projects.map((project) => (
                  <tr key={project.id}>
                    <td className="px-2 py-2">
                      <Link to={`/projects/${project.id}`} className="font-semibold text-text hover:text-brand">{project.projectNumber}</Link>
                      <div className="mt-1 text-xs text-muted">{project.name}</div>
                    </td>
                    <td className="px-2 py-2 text-muted">{project.customerName}</td>
                    <td className="px-2 py-2 text-muted">{project.ownerName || "Unassigned"}</td>
                    <td className="px-2 py-2"><ProjectStatusBadge status={project.status} /></td>
                    <td className="px-2 py-2"><ProjectPriorityBadge priority={project.priority} /></td>
                    <td className="px-2 py-2 text-muted">{project.dueDate ? new Date(project.dueDate).toLocaleDateString() : "No due date"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </section>
  );
}

