"use client";

import { useEffect, useMemo, useState } from "react";
import {
  CopyPlus,
  FolderKanban,
  Pencil,
  Plus,
  Search,
  Sparkles,
  Trash2,
  X,
} from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { ProjectCard } from "@/components/projects/project-card";
import { ProjectForm } from "@/components/projects/project-form";
import { ProjectTemplateForm } from "@/components/projects/project-template-form";
import { SavedViewsBar } from "@/components/tasks/saved-views-bar";
import { useGoals } from "@/hooks/use-goals";
import { useProjectTemplates } from "@/hooks/use-project-templates";
import { useProjects } from "@/hooks/use-projects";
import { useSavedViews } from "@/hooks/use-saved-views";
import { useTeamPermissions } from "@/hooks/use-team-permissions";
import { useTasks } from "@/hooks/use-tasks";
import { cn } from "@/lib/utils";

type ProjectFilterValues = {
  search: string;
  health: string;
  goalId: string;
  approvalStatus: string;
};

const EMPTY_FILTERS: ProjectFilterValues = {
  search: "",
  health: "",
  goalId: "",
  approvalStatus: "",
};

const BUILT_IN_VIEWS = [
  { id: "all", label: "All", filters: {} },
  { id: "at-risk", label: "At risk", filters: { health: "at_risk" } },
  {
    id: "needs-approval",
    label: "Needs approval",
    filters: { approvalStatus: "pending_approval" },
  },
  { id: "approved", label: "Approved", filters: { approvalStatus: "approved" } },
] satisfies Array<{ id: string; label: string; filters: Partial<ProjectFilterValues> }>;

const HEALTH_OPTIONS = [
  { value: "", label: "All health" },
  { value: "on_track", label: "On track" },
  { value: "at_risk", label: "At risk" },
  { value: "stuck", label: "Stuck" },
];

const APPROVAL_OPTIONS = [
  { value: "", label: "All approvals" },
  { value: "pending_approval", label: "Pending" },
  { value: "changes_requested", label: "Changes requested" },
  { value: "approved", label: "Approved" },
  { value: "not_required", label: "No approval" },
];

export default function ProjectsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { projects, loading, createProject, updateProject, deleteProject } =
    useProjects();
  const {
    templates,
    loading: templatesLoading,
    createTemplate,
    updateTemplate,
    deleteTemplate,
  } = useProjectTemplates();
  const { goals } = useGoals();
  const { tasks, createTask } = useTasks();
  const { views, createView, updateView, deleteView } = useSavedViews("projects");
  const { can } = useTeamPermissions();
  const canEditProjects = can("projects", "edit");
  const canEditTasks = can("tasks", "edit");
  const [formOpen, setFormOpen] = useState(false);
  const [editingProject, setEditingProject] = useState<typeof projects[0] | null>(null);
  const [templateFormOpen, setTemplateFormOpen] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<typeof templates[0] | null>(null);
  const [applyingTemplateId, setApplyingTemplateId] = useState<string | null>(null);
  const [filters, setFilters] = useState<ProjectFilterValues>(EMPTY_FILTERS);

  function getTaskCount(projectId: string) {
    return tasks.filter((t) => t.project_id === projectId).length;
  }

  useEffect(() => {
    const savedViewId = searchParams.get("savedView");
    if (!savedViewId || views.length === 0) return;

    const matchedView = views.find((view) => view.id === savedViewId);
    if (!matchedView) return;

    const timer = window.setTimeout(() => {
      setFilters({
        ...EMPTY_FILTERS,
        ...Object.fromEntries(
          Object.entries(matchedView.filters).filter(([, value]) => typeof value === "string")
        ),
      });
    }, 0);

    return () => window.clearTimeout(timer);
  }, [searchParams, views]);

  useEffect(() => {
    const shouldCreate = searchParams.get("create");
    if (shouldCreate !== "1") return;

    const nextParams = new URLSearchParams(searchParams.toString());
    nextParams.delete("create");
    const nextQuery = nextParams.toString();
    router.replace(nextQuery ? `/projects?${nextQuery}` : "/projects", { scroll: false });
    if (canEditProjects) {
      const timer = window.setTimeout(() => {
        setFormOpen(true);
      }, 0);

      return () => window.clearTimeout(timer);
    }
  }, [canEditProjects, router, searchParams]);

  const filteredProjects = useMemo(() => {
    const normalized = filters.search.trim().toLowerCase();

    return projects.filter((project) => {
      if (filters.health && project.health !== filters.health) return false;
      if (filters.goalId && project.goal_id !== filters.goalId) return false;
      if (filters.approvalStatus && project.approval_status !== filters.approvalStatus) {
        return false;
      }

      if (!normalized) return true;

      return [project.name, project.description || "", project.goal || ""]
        .join(" ")
        .toLowerCase()
        .includes(normalized);
    });
  }, [filters, projects]);

  async function handleApplyTemplate(templateId: string) {
    const template = templates.find((item) => item.id === templateId);
    if (!template || !canEditProjects || !canEditTasks) return;

    setApplyingTemplateId(templateId);

    try {
      const project = await createProject({
        name: template.name,
        color: template.color,
        icon: template.icon,
        description: template.description,
        goal: template.goal,
        health: template.health,
      });

      for (const task of template.tasks || []) {
        const deadline =
          typeof task.deadline_offset_days === "number"
            ? new Date(
                Date.now() + task.deadline_offset_days * 24 * 60 * 60 * 1000
              ).toISOString()
            : null;

        await createTask({
          title: task.title,
          description: task.description || undefined,
          priority: task.priority,
          project_id: project.id,
          deadline,
          status: "todo",
        });
      }

      router.push(`/projects/${project.id}`);
    } finally {
      setApplyingTemplateId(null);
    }
  }

  const activeFiltersCount = [filters.health, filters.goalId, filters.approvalStatus].filter(Boolean).length;

  if (loading) {
    return (
      <div className="space-y-8">
        {/* Hero skeleton */}
        <div className="relative overflow-hidden rounded-[28px] border border-white/[0.07] bg-[#0e0c15] p-8">
          <div className="h-8 w-48 rounded-xl bg-white/[0.05] animate-pulse" />
          <div className="mt-3 h-4 w-72 rounded bg-white/[0.04] animate-pulse" />
        </div>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="h-48 rounded-[24px] bg-white/[0.03] border border-white/[0.06] animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">

      {/* ── Hero header ─────────────────────────────────────────────────────── */}
      <div
        className="relative overflow-hidden rounded-[28px] border border-white/[0.07] bg-[#0e0c15] p-8"
        style={{
          backgroundImage:
            "radial-gradient(ellipse at 20% -30%, rgba(109,40,217,0.18) 0%, transparent 60%), radial-gradient(ellipse at 80% 110%, rgba(59,130,246,0.08) 0%, transparent 55%)",
        }}
      >
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-violet-500/20 bg-violet-500/[0.08] px-3 py-1">
              <FolderKanban className="h-3.5 w-3.5 text-violet-400" />
              <span className="text-[10px] font-bold uppercase tracking-[0.18em] text-violet-300">Projects</span>
            </div>
            <h1 className="text-[28px] font-bold tracking-tight text-white">
              {projects.length} {projects.length === 1 ? "Project" : "Projects"}
            </h1>
            <p className="mt-1 text-[14px] text-white/40">
              Organize work, track health, and ship with momentum.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={() =>
                router.push(
                  `/ai?prompt=${encodeURIComponent(
                    "Create a reusable project template for this workspace. I want to describe what should be included, what direction the tasks should go, and the kind of execution rhythm we want. Turn that into a concrete template with starter tasks and timing offsets."
                  )}`
                )
              }
              className="inline-flex items-center gap-2 rounded-xl border border-violet-500/20 bg-violet-500/[0.08] px-4 py-2 text-[13px] font-semibold text-violet-300 transition-all hover:border-violet-500/35 hover:bg-violet-500/[0.14]"
            >
              <Sparkles className="h-3.5 w-3.5" />
              Ask AI
            </button>
            <button
              onClick={() => setTemplateFormOpen(true)}
              disabled={!canEditProjects}
              className="inline-flex items-center gap-2 rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-[13px] font-semibold text-white/70 transition-all hover:border-white/[0.14] hover:bg-white/[0.07] hover:text-white disabled:opacity-40"
            >
              <Sparkles className="h-3.5 w-3.5" />
              New template
            </button>
            <button
              onClick={() => setFormOpen(true)}
              disabled={!canEditProjects}
              className="inline-flex items-center gap-2 rounded-xl border border-violet-500/30 bg-violet-500/[0.15] px-4 py-2 text-[13px] font-bold text-violet-200 transition-all hover:border-violet-500/50 hover:bg-violet-500/[0.22] disabled:opacity-40"
            >
              <Plus className="h-3.5 w-3.5" />
              New project
            </button>
          </div>
        </div>
      </div>

      {/* ── Saved views ─────────────────────────────────────────────────────── */}
      <SavedViewsBar
        filters={filters}
        emptyFilters={EMPTY_FILTERS}
        views={views}
        builtInViews={BUILT_IN_VIEWS}
        title="Saved project views"
        description="Jump straight into the slices that matter, from at-risk work to approval queues."
        onApply={setFilters}
        onCreate={async (name, nextFilters) => {
          await createView({ name, filters: { ...nextFilters } });
        }}
        onDelete={async (id) => {
          await deleteView(id);
        }}
        onToggleFavorite={async (id, isFavorite) => {
          await updateView(id, { is_favorite: isFavorite });
        }}
      />

      {/* ── Filter bar ──────────────────────────────────────────────────────── */}
      <div className="rounded-[22px] border border-white/[0.06] bg-white/[0.025] p-4">
        <div className="flex flex-wrap gap-3">
          {/* Search */}
          <div className="relative min-w-[180px] flex-1">
            <Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-white/25" />
            <input
              value={filters.search}
              onChange={(e) => setFilters((c) => ({ ...c, search: e.target.value }))}
              placeholder="Search projects..."
              className="h-9 w-full rounded-xl border border-white/[0.07] bg-white/[0.04] pl-9 pr-3 text-[13px] text-white/80 placeholder:text-white/25 outline-none focus:border-white/[0.14] focus:bg-white/[0.06] transition-colors"
            />
          </div>

          {/* Health chips */}
          <div className="flex items-center gap-1.5">
            {HEALTH_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                onClick={() => setFilters((c) => ({ ...c, health: c.health === opt.value ? "" : opt.value }))}
                className={cn(
                  "rounded-xl border px-3 py-1.5 text-[12px] font-semibold transition-all",
                  filters.health === opt.value && opt.value !== ""
                    ? "border-violet-500/30 bg-violet-500/[0.15] text-violet-300"
                    : opt.value === ""
                      ? filters.health === ""
                        ? "border-white/[0.12] bg-white/[0.07] text-white/70"
                        : "border-white/[0.06] bg-transparent text-white/35 hover:text-white/55"
                      : "border-white/[0.06] bg-transparent text-white/35 hover:border-white/[0.10] hover:text-white/55",
                )}
              >
                {opt.label}
              </button>
            ))}
          </div>

          {/* Goal select */}
          {goals.length > 0 && (
            <select
              value={filters.goalId}
              onChange={(e) => setFilters((c) => ({ ...c, goalId: e.target.value }))}
              className="h-9 rounded-xl border border-white/[0.07] bg-white/[0.04] px-3 text-[12px] text-white/70 outline-none focus:border-white/[0.14] transition-colors"
            >
              <option value="">All goals</option>
              {goals.map((goal) => (
                <option key={goal.id} value={goal.id}>{goal.title}</option>
              ))}
            </select>
          )}

          {/* Approval chips */}
          <div className="flex items-center gap-1.5">
            {APPROVAL_OPTIONS.filter(o => o.value !== "").map((opt) => (
              <button
                key={opt.value}
                onClick={() => setFilters((c) => ({ ...c, approvalStatus: c.approvalStatus === opt.value ? "" : opt.value }))}
                className={cn(
                  "rounded-xl border px-3 py-1.5 text-[12px] font-semibold transition-all",
                  filters.approvalStatus === opt.value
                    ? "border-sky-500/30 bg-sky-500/[0.12] text-sky-300"
                    : "border-white/[0.06] bg-transparent text-white/35 hover:border-white/[0.10] hover:text-white/55",
                )}
              >
                {opt.label}
              </button>
            ))}
          </div>

          {/* Clear filters */}
          {activeFiltersCount > 0 && (
            <button
              onClick={() => setFilters(EMPTY_FILTERS)}
              className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.06] bg-transparent px-3 py-1.5 text-[12px] text-white/35 transition-all hover:border-white/[0.10] hover:text-white/55"
            >
              <X className="h-3 w-3" />
              Clear
            </button>
          )}
        </div>
      </div>

      {/* ── Template library ────────────────────────────────────────────────── */}
      <div className="rounded-[24px] border border-white/[0.07] bg-[#0e0c15] p-6">
        <div className="mb-5 flex flex-wrap items-start justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="flex h-9 w-9 items-center justify-center rounded-xl border border-violet-500/20 bg-violet-500/[0.10]">
              <Sparkles className="h-4 w-4 text-violet-400" />
            </div>
            <div>
              <h2 className="text-[16px] font-bold tracking-tight text-white">Template library</h2>
              <p className="text-[12px] text-white/35">
                Reusable project starters — launch faster with proven blueprints.
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <span className="rounded-full border border-white/[0.08] bg-white/[0.04] px-2.5 py-0.5 text-[11px] font-semibold text-white/40">
              {templates.length} {templates.length === 1 ? "template" : "templates"}
            </span>
            <button
              onClick={() =>
                router.push(
                  `/ai?prompt=${encodeURIComponent(
                    "Create a reusable project template for this workspace. I want it to include the right starter tasks, clear execution direction, and realistic timing offsets."
                  )}`
                )
              }
              className="inline-flex items-center gap-1.5 rounded-xl border border-violet-500/20 bg-violet-500/[0.08] px-3 py-1.5 text-[12px] font-semibold text-violet-300 transition-all hover:border-violet-500/35 hover:bg-violet-500/[0.14]"
            >
              <Sparkles className="h-3.5 w-3.5" />
              Create with AI
            </button>
          </div>
        </div>

        {templatesLoading ? (
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="h-48 rounded-[20px] bg-white/[0.03] animate-pulse" />
            ))}
          </div>
        ) : templates.length === 0 ? (
          <div className="rounded-[20px] border border-dashed border-white/[0.07] bg-white/[0.01] p-8 text-center">
            <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl border border-white/[0.08] bg-white/[0.04]">
              <Sparkles className="h-5 w-5 text-white/25" />
            </div>
            <p className="text-[14px] font-semibold text-white/40">No templates yet</p>
            <p className="mt-1 text-[12px] text-white/25">
              Build starters for launches, client work, or any workflow you repeat.
            </p>
            <button
              onClick={() => setTemplateFormOpen(true)}
              disabled={!canEditProjects}
              className="mt-4 inline-flex items-center gap-2 rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-[12px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white disabled:opacity-40"
            >
              <Plus className="h-3.5 w-3.5" />
              Create template
            </button>
          </div>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {templates.map((template) => (
              <div
                key={template.id}
                className="group rounded-[20px] border border-white/[0.06] bg-white/[0.025] p-5 transition-all hover:border-white/[0.10] hover:bg-white/[0.04]"
              >
                {/* Icon */}
                <div
                  className="mb-4 flex h-12 w-12 items-center justify-center rounded-[16px] border border-white/[0.08] text-2xl"
                  style={{ backgroundColor: template.color ? `${template.color}18` : "rgba(255,255,255,0.04)" }}
                >
                  {template.icon}
                </div>

                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0 flex-1">
                    <h3 className="truncate text-[14px] font-bold text-white/90">{template.name}</h3>
                    {template.description && (
                      <p className="mt-1 line-clamp-2 text-[12px] leading-relaxed text-white/40">
                        {template.description}
                      </p>
                    )}
                  </div>
                  <span className="shrink-0 rounded-full border border-white/[0.07] bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold text-white/35">
                    {(template.tasks || []).length} tasks
                  </span>
                </div>

                {template.goal && (
                  <p className="mt-3 text-[11px] text-violet-400/70 line-clamp-2">
                    🎯 {template.goal}
                  </p>
                )}

                <div className="mt-4 flex flex-wrap gap-2">
                  <button
                    onClick={() => void handleApplyTemplate(template.id)}
                    disabled={!canEditProjects || !canEditTasks || applyingTemplateId === template.id}
                    className="inline-flex items-center gap-1.5 rounded-xl border border-violet-500/25 bg-violet-500/[0.10] px-3 py-1.5 text-[12px] font-semibold text-violet-300 transition-all hover:border-violet-500/40 hover:bg-violet-500/[0.18] disabled:opacity-40"
                  >
                    <CopyPlus className="h-3.5 w-3.5" />
                    {applyingTemplateId === template.id ? "Applying…" : "Use template"}
                  </button>
                  <button
                    onClick={() => setEditingTemplate(template)}
                    disabled={!canEditProjects}
                    className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.07] bg-transparent px-3 py-1.5 text-[12px] font-semibold text-white/40 transition-all hover:border-white/[0.12] hover:text-white/65 disabled:opacity-40"
                  >
                    <Pencil className="h-3 w-3" />
                    Edit
                  </button>
                  <button
                    onClick={() => void deleteTemplate(template.id)}
                    disabled={!canEditProjects}
                    className="inline-flex items-center gap-1.5 rounded-xl border border-transparent px-2 py-1.5 text-[12px] text-white/25 transition-all hover:border-red-500/20 hover:bg-red-500/[0.08] hover:text-red-400 disabled:opacity-40"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── Projects grid ───────────────────────────────────────────────────── */}
      {filteredProjects.length === 0 ? (
        <div className="rounded-[24px] border border-dashed border-white/[0.07] bg-white/[0.01] p-12 text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-3xl border border-white/[0.08] bg-white/[0.04]">
            <FolderKanban className="h-7 w-7 text-white/25" />
          </div>
          <p className="text-[16px] font-bold text-white/40">
            {projects.length === 0 ? "No projects yet" : "No matching projects"}
          </p>
          <p className="mt-2 text-[13px] text-white/25">
            {projects.length === 0
              ? "Create a project or start from a template to organize tasks and notes faster."
              : "Try another saved view or loosen your filters."}
          </p>
          {projects.length === 0 && (
            <div className="mt-5 flex flex-wrap items-center justify-center gap-2">
              <button
                onClick={() => setTemplateFormOpen(true)}
                disabled={!canEditProjects}
                className="inline-flex items-center gap-2 rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-[13px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white disabled:opacity-40"
              >
                <Sparkles className="h-3.5 w-3.5" />
                Create template
              </button>
              <button
                onClick={() => setFormOpen(true)}
                disabled={!canEditProjects}
                className="inline-flex items-center gap-2 rounded-xl border border-violet-500/30 bg-violet-500/[0.15] px-4 py-2 text-[13px] font-bold text-violet-200 transition-all hover:border-violet-500/50 hover:bg-violet-500/[0.22] disabled:opacity-40"
              >
                <Plus className="h-3.5 w-3.5" />
                Create project
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {filteredProjects.map((project) => (
            <ProjectCard
              key={project.id}
              project={project}
              taskCount={getTaskCount(project.id)}
              goalTitle={goals.find((goal) => goal.id === project.goal_id)?.title || null}
              onEdit={() => setEditingProject(project)}
              onDelete={() => deleteProject(project.id)}
              canManage={canEditProjects}
            />
          ))}
        </div>
      )}

      {/* ── Modals ──────────────────────────────────────────────────────────── */}
      {formOpen && (
        <ProjectForm
          open={formOpen}
          onClose={() => setFormOpen(false)}
          onSubmit={async (data) => { await createProject(data); }}
          goals={goals}
        />
      )}

      {editingProject && (
        <ProjectForm
          open={!!editingProject}
          onClose={() => setEditingProject(null)}
          onSubmit={async (data) => { await updateProject(editingProject.id, data); }}
          project={editingProject}
          goals={goals}
        />
      )}

      {templateFormOpen && (
        <ProjectTemplateForm
          open={templateFormOpen}
          onClose={() => setTemplateFormOpen(false)}
          onSubmit={async (data) => {
            await createTemplate(data);
          }}
        />
      )}

      {editingTemplate && (
        <ProjectTemplateForm
          open={!!editingTemplate}
          onClose={() => setEditingTemplate(null)}
          onSubmit={async (data) => {
            await updateTemplate(editingTemplate.id, data);
            setEditingTemplate(null);
          }}
          template={editingTemplate}
        />
      )}
    </div>
  );
}
