"use client";

import type { ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { getProjectTableColumns } from "@/data/source/projects";
import type { ProjectPriority, ProjectRow, ProjectStatus } from "@/types/project";
import { ArrowLeft, FolderKanban, Plus } from "lucide-react";
import Link from "next/link";
import { useMemo, useState } from "react";
import ProjectsCardToolbar from "./projects-card-toolbar";
import ProjectsFilledPanel from "./projects-filled-panel";

type Props = {
  app: string;
  data: ProjectRow[];
};

export default function ProjectsPageBody({ app, data }: Props) {
  const [search, setSearch] = useState("");
  const [rows, setRows] = useState<ProjectRow[]>(data);

  const columns = useMemo(
    () =>
      getProjectTableColumns(app, {
        onPriorityChange: (rowId, next) => {
          setRows((prev) => prev.map((r) => (r.id === rowId ? { ...r, priority: next as ProjectPriority } : r)));
        },
        onStatusChange: (rowId, next) => {
          setRows((prev) => prev.map((r) => (r.id === rowId ? { ...r, status: next as ProjectStatus } : r)));
        },
      }),
    [app],
  );

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((row) =>
      [row.name, row.displayId, row.leaderName, row.status, row.priority].some((field) =>
        String(field).toLowerCase().includes(q),
      ),
    );
  }, [rows, search]);

  const newProjectHref = `/${app}/projects/new`;
  const taskBoardHref = `/${app}/projects/1/task-board`;
  const dashboardHref = `/${app}/dashboard`;

  const pageActions = (
    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
      <div className="flex items-center gap-2">
        <Link href={dashboardHref} className="inline-flex rounded bg-white p-2 text-[#383E49]">
          <ArrowLeft className="size-4" />
        </Link>
        <h1 className="text-[30px] font-semibold leading-none text-[#272833]">All Projects</h1>
      </div>

      <div className="flex items-center gap-2">
        <Link href={taskBoardHref}>
          <Button
            variant="outline"
            className="h-8 rounded border border-[#E5E7EB] bg-white px-4 text-[11px] font-medium text-[#272833] hover:bg-white"
          >
            View Task board
          </Button>
        </Link>
        <Link href={newProjectHref}>
          <Button className="h-8 rounded bg-[#074473] px-4 text-[11px] font-medium text-white hover:bg-[#074473]/90">
            Add New Project
          </Button>
        </Link>
      </div>
    </div>
  );

  const mainCard = (body: ReactNode) => (
    <Card className="border border-[#EBEEF2] bg-white shadow-sm">
      <CardContent className="space-y-6 p-4 sm:p-6">{body}</CardContent>
    </Card>
  );

  if (rows.length === 0) {
    return (
      <div className="min-w-0 space-y-6">
        {pageActions}
        {mainCard(
          <>
            <ProjectsCardToolbar searchValue={search} onSearchChange={setSearch} />
            <div className="flex flex-col items-center justify-center gap-9 py-10 sm:py-14">
              <div className="flex size-[123px] shrink-0 items-center justify-center rounded-full border border-[#E1E2E9] bg-[#F4F5FA]">
                <FolderKanban className="size-[52px] text-[#383E49]" strokeWidth={1.25} aria-hidden />
              </div>
              <div className="flex max-w-sm flex-col items-center gap-6 text-center">
                <div className="space-y-2.5">
                  <p className="text-lg font-bold text-black">No project added</p>
                  <p className="text-base text-[#8B8D97]">Create a project to see it listed here.</p>
                </div>
                <Button
                  asChild
                  className="inline-flex h-[42px] items-center gap-2 rounded-md bg-[#074473] px-6 text-sm font-medium text-white hover:bg-[#074473]/90"
                >
                  <Link href={newProjectHref}>
                    <Plus className="size-4 shrink-0" aria-hidden />
                    Add New Project
                  </Link>
                </Button>
              </div>
            </div>
          </>,
        )}
      </div>
    );
  }

  return (
    <div className="min-w-0 space-y-6">
      {pageActions}
      {mainCard(
        <>
          <ProjectsCardToolbar searchValue={search} onSearchChange={setSearch} />
          <ProjectsFilledPanel data={filtered} columns={columns} />
        </>,
      )}
    </div>
  );
}
