import {
  Calendar,
  CheckCircle2,
  Clock,
  FileText,
  GitBranch,
  Globe,
  ListChecks,
  Plug,
  Sparkles,
  UserCheck,
  Webhook,
} from "lucide-react";
import { prisma } from "@/lib/db/prisma";
import { ModuleFoundationView } from "@/components/shared/module-foundation-view";
import { StatusBadge } from "@/components/shared/status-badge";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";

export const dynamic = "force-dynamic";

async function getWorkflowCount(): Promise<number | null> {
  try {
    return await prisma.workflow.count();
  } catch {
    return null;
  }
}

const PREVIEW_STAGES = [
  {
    name: "DAY 0 — PRE-START",
    headerBg: "bg-blue-50/80 border-blue-100 text-blue-800",
    tasks: [
      { title: "Send welcome packet & employment documents", dept: "HR", due: "-5d", sub: "Before start", done: true },
      { title: "Prepare laptop, peripherals & company access card", dept: "Admin", due: "-5d", sub: "Before start", done: true },
      { title: "Provision Microsoft 365, Entra ID MFA & Teams", dept: "IT", due: "-3d", sub: "Before start", done: false },
    ],
  },
  {
    name: "DAY 1 — ORIENTATION & ACCESS",
    headerBg: "bg-emerald-50/80 border-emerald-100 text-emerald-800",
    tasks: [
      { title: "Configure Ramco ERP & Freshservice access", dept: "IT", due: "D1 · 9:00 AM", sub: "On start date", done: false },
      { title: "Conduct SMC Cement Group HR orientation & safety briefing", dept: "HR", due: "D1 · 10:00 AM", sub: "On start date", done: false },
    ],
  },
  {
    name: "WEEK 1 — INTEGRATION",
    headerBg: "bg-violet-50/80 border-violet-100 text-violet-800",
    tasks: [
      { title: "Department role & expectations alignment", dept: "Manager", due: "Day 3", sub: "After start", done: false },
      { title: "Complete cybersecurity & Data Privacy Act (RA 10173) training", dept: "Employee", due: "Day 5", sub: "After start", done: false },
    ],
  },
];

export default async function WorkflowsPage() {
  const count = await getWorkflowCount();

  return (
    <ModuleFoundationView
      title="Workflow Builder"
      description="Design, version, and publish executable multi-department lifecycle templates with relative due dates and dependencies."
      phaseLabel="Phase 7 — Visual Engine"
      schemaEntities={["Workflow", "WorkflowVersion", "WorkflowStage", "WorkflowTaskTemplate"]}
      recordCount={count}
      plannedCapabilities={[
        "Drag-and-drop stage & task workflow designer",
        "7 default SMC templates (Onboarding, Offboarding, Emergency, Transfers)",
        "Basic nodes: Task, Approval, Form, Meeting, Training, Document Request",
        "Advanced nodes: Condition, Delay, Webhook, Integration Action, Notification",
        "Draft / Published / Archived versioning with immutable execution snapshots",
        "Task dependency graph & relative start/LWD due-date engine",
      ]}
    >
      {/* Visual Design Blueprint Preview matching the Crewly reference */}
      <div className="space-y-4">
        <Card className="grid divide-y divide-[#E5E7EB] sm:grid-cols-2 sm:divide-y-0 lg:grid-cols-4 lg:divide-x">
          {[
            { icon: FileText, label: "TEMPLATE", value: "Standard Employee Onboarding" },
            { icon: Calendar, label: "DATE REFERENCE", value: "Employee start date" },
            { icon: Globe, label: "TIME ZONE", value: "Asia/Manila (PHT)" },
            { icon: ListChecks, label: "DEFAULT TEMPLATES", value: "7 published blueprints" },
          ].map((meta) => (
            <div key={meta.label} className="flex items-center gap-3 p-4">
              <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] text-[#475569]">
                <meta.icon className="h-4 w-4" />
              </div>
              <div className="min-w-0">
                <p className="text-[10px] font-semibold uppercase tracking-wider text-[#64748B]">
                  {meta.label}
                </p>
                <p className="truncate text-xs font-semibold text-[#111827]">{meta.value}</p>
              </div>
            </div>
          ))}
        </Card>

        <div className="grid gap-5 lg:grid-cols-12">
          <div className="space-y-4 lg:col-span-9">
            {PREVIEW_STAGES.map((stage) => (
              <div
                key={stage.name}
                className="overflow-hidden rounded-xl border border-[#E5E7EB] bg-white shadow-card"
              >
                <div className={`flex items-center justify-between border-b px-4 py-2.5 text-[11px] font-semibold tracking-wider ${stage.headerBg}`}>
                  <span>{stage.name}</span>
                  <StatusBadge status="PUBLISHED" showDot={false} />
                </div>
                <div className="divide-y divide-[#F1F5F9]">
                  {stage.tasks.map((task) => (
                    <div
                      key={task.title}
                      className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 text-xs"
                    >
                      <div className="flex items-center gap-3">
                        {task.done ? (
                          <CheckCircle2 className="h-4 w-4 shrink-0 text-status-success" />
                        ) : (
                          <span className="h-4 w-4 shrink-0 rounded-full border-2 border-[#CBD5E1]" />
                        )}
                        <span className="font-medium text-[#111827]">{task.title}</span>
                      </div>
                      <div className="flex items-center gap-3">
                        <Badge variant="default">{task.dept}</Badge>
                        <div className="min-w-[84px] text-right">
                          <p className="font-mono text-[11px] font-semibold text-[#111827]">
                            {task.due}
                          </p>
                          <p className="text-[10px] text-[#64748B]">{task.sub}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>

          <Card className="h-fit p-4 lg:col-span-3">
            <h3 className="text-xs font-semibold text-[#111827]">Workflow Components</h3>
            <p className="mt-0.5 text-[11px] text-[#64748B]">
              Interactive drag-and-drop builder activates in Phase 7.
            </p>
            <div className="mt-4 space-y-3">
              <div>
                <p className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-[#94A3B8]">
                  Basic Tasks
                </p>
                <div className="space-y-1.5 text-xs text-[#334155]">
                  {[
                    { icon: ListChecks, label: "Task" },
                    { icon: UserCheck, label: "Approval" },
                    { icon: FileText, label: "Form / Document Request" },
                    { icon: Calendar, label: "Meeting / Training" },
                  ].map((item) => (
                    <div
                      key={item.label}
                      className="flex items-center gap-2 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 py-2"
                    >
                      <item.icon className="h-3.5 w-3.5 text-[#64748B]" />
                      <span>{item.label}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <p className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-[#94A3B8]">
                  Advanced
                </p>
                <div className="space-y-1.5 text-xs text-[#334155]">
                  {[
                    { icon: GitBranch, label: "Condition" },
                    { icon: Clock, label: "Delay" },
                    { icon: Webhook, label: "Webhook" },
                    { icon: Plug, label: "Integration Action" },
                  ].map((item) => (
                    <div
                      key={item.label}
                      className="flex items-center gap-2 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 py-2"
                    >
                      <item.icon className="h-3.5 w-3.5 text-brand" />
                      <span>{item.label}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="rounded-lg border border-brand-border bg-brand-soft p-2.5 text-[11px] text-brand">
                <span className="flex items-center gap-1 font-semibold">
                  <Sparkles className="h-3 w-3" /> Relative Scheduling
                </span>
                <p className="mt-1 text-[#334155]">
                  Due dates calculate automatically from Start Date, LWD, or Effective Date (-5d, D1, Day 3).
                </p>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </ModuleFoundationView>
  );
}
