"use client";

import { FolderOpen, Pause, Play, Plus, Trash2 } from "lucide-react";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { DashboardLayout } from "@/components/layout/dashboard-layout";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { fetchGeneratedPosts } from "@/lib/client/generation-api";
import { useProjectsStore } from "@/store/projects-store";

export default function DashboardPage() {
  const projects = useProjectsStore((s) => (Array.isArray(s.projects) ? s.projects : []));
  const activeProjectId = useProjectsStore((s) => s.activeProjectId);
  const switchProject = useProjectsStore((s) => s.switchProject);
  const deleteProject = useProjectsStore((s) => s.deleteProject);
  const updateProject = useProjectsStore((s) => s.updateProject);
  const getProjectData = useProjectsStore((s) => s.getProjectData);

  const [postCounts, setPostCounts] = useState<Record<string, number>>({});

  const loadCounts = useCallback(async () => {
    const entries = await Promise.all(
      projects.map(async (p) => {
        const posts = await fetchGeneratedPosts(p.id, p.name);
        return [p.id, posts.length] as const;
      }),
    );
    setPostCounts(Object.fromEntries(entries));
  }, [projects]);

  useEffect(() => {
    void loadCounts();
  }, [loadCounts]);

  return (
    <DashboardLayout>
      <PageHeader
        title="My Projects"
        subtitle="Create, switch, pause, or open a project workspace"
      />
      <div className="flex-1 px-4 pb-8 pt-2 sm:px-6 lg:px-8">
        <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
          <p className="text-sm text-gray-600">
            {projects.length} project{projects.length === 1 ? "" : "s"}
          </p>
          <Link
            href="/my-project?new=1"
            className="inline-flex items-center justify-center gap-2 rounded-[var(--radius-button)] bg-action px-3 py-1.5 text-sm text-white shadow-sm hover:bg-action-hover"
          >
            <Plus className="h-4 w-4" />
            New project
          </Link>
        </div>

        {projects.length === 0 ? (
          <Card className="mx-auto max-w-lg p-8 text-center">
            <p className="text-lg font-semibold text-gray-900">No projects yet</p>
            <p className="mt-2 text-sm text-gray-500">
              Create your first project to set up brand, context, and posting.
            </p>
            <Link
              href="/my-project?new=1"
              className="mt-6 inline-flex items-center justify-center rounded-[var(--radius-button)] bg-action px-5 py-2.5 text-sm font-medium text-white"
            >
              Create project
            </Link>
          </Card>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {projects.map((project) => {
              const data = getProjectData(project.id);
              const isActive = project.id === activeProjectId;
              const contextSaved = data?.context.saved ?? false;

              return (
                <Card
                  key={project.id}
                  className={cn(
                    "flex flex-col p-5",
                    isActive && "ring-2 ring-brand-600 ring-offset-2",
                  )}
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0">
                      <h2 className="truncate text-base font-semibold text-gray-900">
                        {project.name}
                      </h2>
                      <p className="mt-1 text-xs text-gray-500">{project.industry}</p>
                    </div>
                    <span
                      className={cn(
                        "shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",
                        project.status === "active"
                          ? "bg-green-100 text-green-700"
                          : "bg-amber-100 text-amber-800",
                      )}
                    >
                      {project.status === "active" ? "Active" : "Paused"}
                    </span>
                  </div>

                  <dl className="mt-4 grid grid-cols-2 gap-3 text-sm">
                    <div>
                      <dt className="text-xs text-gray-400">Generated posts</dt>
                      <dd className="font-semibold text-gray-900">
                        {postCounts[project.id] ?? "—"}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-xs text-gray-400">Context</dt>
                      <dd className="font-semibold text-gray-900">
                        {contextSaved ? "Saved" : "Draft"}
                      </dd>
                    </div>
                  </dl>

                  <div className="mt-5 flex flex-wrap gap-2">
                    {!isActive && (
                      <Button
                        type="button"
                        size="sm"
                        variant="secondary"
                        onClick={() => switchProject(project.id)}
                      >
                        <FolderOpen className="h-3.5 w-3.5" />
                        Switch
                      </Button>
                    )}
                    {isActive && (
                      <span className="inline-flex items-center rounded-md bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700">
                        Current project
                      </span>
                    )}
                    <Link
                      href={`/my-project?edit=${project.id}`}
                      className="inline-flex items-center justify-center gap-2 rounded-[var(--radius-button)] px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100"
                    >
                      Edit
                    </Link>
                    <Button
                      type="button"
                      size="sm"
                      variant="ghost"
                      onClick={() =>
                        updateProject(project.id, {
                          status: project.status === "active" ? "paused" : "active",
                        })
                      }
                    >
                      {project.status === "active" ? (
                        <>
                          <Pause className="h-3.5 w-3.5" />
                          Pause
                        </>
                      ) : (
                        <>
                          <Play className="h-3.5 w-3.5" />
                          Resume
                        </>
                      )}
                    </Button>
                    {projects.length > 1 && (
                      <Button
                        type="button"
                        size="sm"
                        variant="ghost"
                        className="text-red-600 hover:text-red-700"
                        onClick={() => {
                          if (
                            confirm(
                              `Delete "${project.name}"? This cannot be undone.`,
                            )
                          ) {
                            deleteProject(project.id);
                          }
                        }}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                        Delete
                      </Button>
                    )}
                  </div>

                  {isActive && (
                    <div className="mt-4 flex gap-2 border-t border-gray-100 pt-4">
                    <Link
                      href="/posting-context"
                      className="inline-flex flex-1 items-center justify-center gap-2 rounded-[var(--radius-button)] bg-brand-600 px-3 py-1.5 text-sm text-white hover:bg-brand-700"
                    >
                      {project.status === "active" ? (
                        <Play className="h-3.5 w-3.5" />
                      ) : (
                        <Pause className="h-3.5 w-3.5" />
                      )}
                      Open workflow
                    </Link>
                    </div>
                  )}
                </Card>
              );
            })}
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
