"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  Activity,
  AlertCircle,
  ArrowRight,
  CalendarClock,
  CheckCircle2,
  ClipboardCheck,
  Clock,
  Database,
  Filter,
  Laptop,
  RotateCcw,
  ShieldCheck,
  UserMinus,
  UserPlus,
  Users,
} from "lucide-react";
import type { DashboardPayload } from "@/services/dashboard.service";
import { SMC_COMPANIES } from "@/lib/config/navigation";
import {
  formatDaysUntil,
  formatRelativeTimestamp,
  formatShortDate,
} from "@/lib/utils";
import { PageHeader } from "@/components/shared/page-header";
import { KpiCard } from "@/components/shared/kpi-card";
import { StatusBadge } from "@/components/shared/status-badge";
import { CompanyPill } from "@/components/shared/company-pill";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

interface DashboardViewProps {
  data: DashboardPayload;
}

export function DashboardView({ data }: DashboardViewProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const updateFilter = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString());
    if (!value || value === "ALL" || value === "30d") {
      if (key === "dateRange" && value === "30d") {
        params.delete(key);
      } else if (value === "ALL") {
        params.delete(key);
      } else {
        params.set(key, value);
      }
    } else {
      params.set(key, value);
    }
    const qs = params.toString();
    router.push(qs ? `${pathname}?${qs}` : pathname);
  };

  const resetFilters = () => {
    router.push(pathname);
  };

  const hasActiveFilters =
    data.filters.company !== "ALL" ||
    data.filters.department !== "ALL" ||
    data.filters.dateRange !== "30d" ||
    data.filters.requestType !== "ALL" ||
    data.filters.status !== "ALL";

  const maxOverviewValue = Math.max(
    1,
    ...data.lifecycleOverview.map((d) => d.onboarding + d.offboarding + d.movement)
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <PageHeader
        title="Management Dashboard"
        description="Real-time employee lifecycle visibility across Eagle Cement (ECC), Northern Cement (NCC), and Solid Cement (SCII)."
        badge={
          data.dataSource === "POSTGRESQL_LIVE" ? (
            <Badge variant="success">
              <Database className="h-3 w-3" />
              PostgreSQL Live
            </Badge>
          ) : (
            <Badge variant="warning">
              <Database className="h-3 w-3" />
              Dev Preview Mode
            </Badge>
          )
        }
        actions={
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" asChild>
              <Link href="/reports">View Reports</Link>
            </Button>
            <Button size="sm" asChild>
              <Link href="/onboarding">
                <UserPlus className="h-3.5 w-3.5" />
                Onboarding Queue
              </Link>
            </Button>
          </div>
        }
      />

      {/* Transparent DB Setup Banner if fallback active */}
      {data.dataSourceNotice && (
        <div className="flex items-start gap-2.5 rounded-xl border border-amber-200 bg-amber-50/70 px-4 py-3 text-xs text-amber-900">
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
          <p className="leading-relaxed">{data.dataSourceNotice}</p>
        </div>
      )}

      {/* Filter Bar */}
      <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[#E5E7EB] bg-white px-4 py-3 shadow-subtle">
        <div className="flex flex-wrap items-center gap-2.5">
          <span className="flex items-center gap-1.5 text-xs font-semibold text-[#475569]">
            <Filter className="h-3.5 w-3.5 text-[#64748B]" />
            Filters
          </span>

          <select
            aria-label="Filter by company"
            value={data.filters.company}
            onChange={(e) => updateFilter("company", e.target.value)}
            className="h-8 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 text-xs font-medium text-[#111827] focus:border-brand focus:outline-none"
          >
            {SMC_COMPANIES.map((c) => (
              <option key={c.code} value={c.code}>
                {c.name}
              </option>
            ))}
          </select>

          <select
            aria-label="Filter by department"
            value={data.filters.department}
            onChange={(e) => updateFilter("department", e.target.value)}
            className="h-8 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 text-xs font-medium text-[#111827] focus:border-brand focus:outline-none"
          >
            <option value="ALL">All Departments</option>
            {data.departments.map((d) => (
              <option key={d.code} value={d.name}>
                {d.name}
              </option>
            ))}
          </select>

          <select
            aria-label="Filter by date range"
            value={data.filters.dateRange}
            onChange={(e) => updateFilter("dateRange", e.target.value)}
            className="h-8 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 text-xs font-medium text-[#111827] focus:border-brand focus:outline-none"
          >
            <option value="7d">Last 7 days</option>
            <option value="30d">Last 30 days</option>
            <option value="90d">Last 90 days</option>
            <option value="all">All time</option>
          </select>

          <select
            aria-label="Filter by request type"
            value={data.filters.requestType}
            onChange={(e) => updateFilter("requestType", e.target.value)}
            className="h-8 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 text-xs font-medium text-[#111827] focus:border-brand focus:outline-none"
          >
            <option value="ALL">All Request Types</option>
            <option value="ONBOARDING">Onboarding</option>
            <option value="OFFBOARDING">Offboarding</option>
            <option value="MOVEMENT">Movement / Transfer</option>
          </select>

          <select
            aria-label="Filter by status"
            value={data.filters.status}
            onChange={(e) => updateFilter("status", e.target.value)}
            className="h-8 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-2.5 text-xs font-medium text-[#111827] focus:border-brand focus:outline-none"
          >
            <option value="ALL">All Statuses</option>
            <option value="IN_PROGRESS">In Progress</option>
            <option value="PENDING_APPROVAL">Pending Approval</option>
            <option value="COMPLETED">Completed</option>
          </select>
        </div>

        {hasActiveFilters && (
          <Button variant="ghost" size="sm" onClick={resetFilters}>
            <RotateCcw className="h-3.5 w-3.5" />
            Reset
          </Button>
        )}
      </div>

      {/* 8 KPI Cards */}
      <section aria-label="Key Performance Indicators" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <KpiCard
          title="Total Active Employees"
          value={data.kpis.totalActiveEmployees}
          subtitle="Authorized scope"
          icon={<Users className="h-4 w-4" />}
          tone="default"
          href="/people"
        />
        <KpiCard
          title="Employees Onboarding"
          value={data.kpis.employeesOnboarding}
          subtitle="Active requests"
          icon={<UserPlus className="h-4 w-4" />}
          tone="info"
          href="/onboarding"
        />
        <KpiCard
          title="Employees Offboarding"
          value={data.kpis.employeesOffboarding}
          subtitle="Clearance active"
          icon={<UserMinus className="h-4 w-4" />}
          tone="warning"
          href="/offboarding"
        />
        <KpiCard
          title="Pending Approvals"
          value={data.kpis.pendingApprovals}
          subtitle="Awaiting sign-off"
          icon={<ClipboardCheck className="h-4 w-4" />}
          tone="warning"
          href="/onboarding"
        />
        <KpiCard
          title="Pending IT Tasks"
          value={data.kpis.pendingItTasks}
          subtitle="Provisioning & access"
          icon={<Laptop className="h-4 w-4" />}
          tone="default"
          href="/tasks"
        />
        <KpiCard
          title="Overdue Tasks"
          value={data.kpis.overdueTasks}
          subtitle="Requires escalation"
          icon={<AlertCircle className="h-4 w-4" />}
          tone={data.kpis.overdueTasks > 0 ? "danger" : "success"}
          href="/tasks"
        />
        <KpiCard
          title="Upcoming Start Dates"
          value={data.kpis.upcomingStartDates}
          subtitle="Next 14 days"
          icon={<CalendarClock className="h-4 w-4" />}
          tone="success"
          href="/onboarding"
        />
        <KpiCard
          title="Upcoming Separation Dates"
          value={data.kpis.upcomingSeparationDates}
          subtitle="Next 14 days"
          icon={<Clock className="h-4 w-4" />}
          tone="danger"
          href="/offboarding"
        />
      </section>

      {/* Row 1: Lifecycle Overview + SLA & Completion Performance */}
      <div className="grid gap-5 lg:grid-cols-12">
        <Card className="lg:col-span-8">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
            <div>
              <CardTitle>Employee Lifecycle Overview</CardTitle>
              <CardDescription>
                Volume distribution across onboarding, offboarding, and movement workflows
              </CardDescription>
            </div>
            <div className="flex items-center gap-3 text-[11px] font-medium text-[#64748B]">
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-full bg-brand" /> Onboarding
              </span>
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-full bg-amber-500" /> Offboarding
              </span>
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-full bg-violet-500" /> Movement
              </span>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid h-48 grid-cols-6 items-end gap-3 pt-4">
              {data.lifecycleOverview.map((bucket) => {
                const total = bucket.onboarding + bucket.offboarding + bucket.movement;
                const onbH = Math.max(4, Math.round((bucket.onboarding / maxOverviewValue) * 140));
                const offH = Math.max(3, Math.round((bucket.offboarding / maxOverviewValue) * 140));
                const movH = Math.max(2, Math.round((bucket.movement / maxOverviewValue) * 140));

                return (
                  <div key={bucket.label} className="flex flex-col items-center gap-2">
                    <span className="font-mono text-[10px] font-medium text-[#64748B]">
                      {total}
                    </span>
                    <div className="flex w-full max-w-[44px] flex-col-reverse overflow-hidden rounded-t-md bg-[#F1F5F9]">
                      <div style={{ height: `${onbH}px` }} className="w-full bg-brand/90" />
                      <div style={{ height: `${offH}px` }} className="w-full bg-amber-400" />
                      <div style={{ height: `${movH}px` }} className="w-full bg-violet-400" />
                    </div>
                    <span className="text-[11px] font-medium text-[#64748B]">{bucket.label}</span>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>

        <Card className="lg:col-span-4">
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2">
              <ShieldCheck className="h-4 w-4 text-status-success" />
              SLA &amp; Completion Performance
            </CardTitle>
            <CardDescription>Operational timeliness and security verification metrics</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {[
              {
                label: "On-Time Task SLA Rate",
                value: `${data.slaPerformance.onTimeCompletionRate}%`,
                pct: data.slaPerformance.onTimeCompletionRate,
                bar: "bg-brand",
              },
              {
                label: "Account Deactivation Compliance",
                value: `${data.slaPerformance.deactivationComplianceRate}%`,
                pct: data.slaPerformance.deactivationComplianceRate,
                bar: "bg-status-success",
              },
              {
                label: "Asset Recovery Clearance Rate",
                value: `${data.slaPerformance.assetRecoveryRate}%`,
                pct: data.slaPerformance.assetRecoveryRate,
                bar: "bg-sky-500",
              },
            ].map((metric) => (
              <div key={metric.label} className="space-y-1.5">
                <div className="flex items-center justify-between text-xs">
                  <span className="font-medium text-[#334155]">{metric.label}</span>
                  <span className="font-mono font-semibold text-[#111827]">{metric.value}</span>
                </div>
                <div className="h-2 w-full overflow-hidden rounded-full bg-[#F1F5F9]">
                  <div
                    className={`h-full rounded-full ${metric.bar}`}
                    style={{ width: `${Math.min(100, metric.pct)}%` }}
                  />
                </div>
              </div>
            ))}

            <div className="flex items-center justify-between rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-3 py-2.5 text-xs">
              <span className="text-[#64748B]">Avg. IT Provisioning Lead Time</span>
              <span className="font-mono font-semibold text-[#111827]">
                {data.slaPerformance.avgProvisioningHours} hrs
              </span>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Row 2: Upcoming Onboarding & Upcoming Offboarding */}
      <div className="grid gap-5 lg:grid-cols-2">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
            <div>
              <CardTitle>Upcoming Onboarding</CardTitle>
              <CardDescription>Scheduled new hires and readiness progress</CardDescription>
            </div>
            <Link
              href="/onboarding"
              className="inline-flex items-center gap-1 text-xs font-medium text-brand hover:underline"
            >
              View all <ArrowRight className="h-3 w-3" />
            </Link>
          </CardHeader>
          <CardContent>
            {data.upcomingOnboarding.length === 0 ? (
              <p className="py-6 text-center text-xs text-[#64748B]">
                No upcoming onboarding requests match the current filter.
              </p>
            ) : (
              <div className="divide-y divide-[#F1F5F9]">
                {data.upcomingOnboarding.map((item) => (
                  <div key={item.id} className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
                    <div className="min-w-0 space-y-0.5">
                      <div className="flex items-center gap-2">
                        <span className="truncate text-xs font-semibold text-[#111827]">
                          {item.employeeName}
                        </span>
                        <CompanyPill code={item.companyCode} />
                      </div>
                      <p className="truncate text-[11px] text-[#64748B]">
                        {item.positionTitle} · {item.departmentName}
                      </p>
                      <p className="font-mono text-[10px] text-[#94A3B8]">{item.requestNumber}</p>
                    </div>

                    <div className="flex shrink-0 flex-col items-end gap-1.5">
                      <div className="flex items-center gap-2">
                        <span className="text-[11px] font-medium text-[#334155]">
                          {formatShortDate(item.targetDate)}
                        </span>
                        <StatusBadge status={item.status} showDot={false} />
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="h-1.5 w-24 overflow-hidden rounded-full bg-[#E2E8F0]">
                          <div
                            className="h-full rounded-full bg-brand"
                            style={{ width: `${item.completionPercent}%` }}
                          />
                        </div>
                        <span className="font-mono text-[10px] text-[#64748B]">
                          {item.completionPercent}%
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
            <div>
              <CardTitle>Upcoming Offboarding</CardTitle>
              <CardDescription>Scheduled separations, account revocation &amp; clearance</CardDescription>
            </div>
            <Link
              href="/offboarding"
              className="inline-flex items-center gap-1 text-xs font-medium text-brand hover:underline"
            >
              View all <ArrowRight className="h-3 w-3" />
            </Link>
          </CardHeader>
          <CardContent>
            {data.upcomingOffboarding.length === 0 ? (
              <p className="py-6 text-center text-xs text-[#64748B]">
                No upcoming offboarding requests match the current filter.
              </p>
            ) : (
              <div className="divide-y divide-[#F1F5F9]">
                {data.upcomingOffboarding.map((item) => (
                  <div key={item.id} className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
                    <div className="min-w-0 space-y-0.5">
                      <div className="flex items-center gap-2">
                        <span className="truncate text-xs font-semibold text-[#111827]">
                          {item.employeeName}
                        </span>
                        <CompanyPill code={item.companyCode} />
                        {item.badgeDetail && (
                          <Badge variant={item.badgeDetail === "EMERGENCY" ? "danger" : "secondary"}>
                            {item.badgeDetail.replaceAll("_", " ")}
                          </Badge>
                        )}
                      </div>
                      <p className="truncate text-[11px] text-[#64748B]">
                        {item.positionTitle} · {item.departmentName}
                      </p>
                      <p className="font-mono text-[10px] text-[#94A3B8]">{item.requestNumber}</p>
                    </div>

                    <div className="flex shrink-0 flex-col items-end gap-1.5">
                      <div className="flex items-center gap-2">
                        <span className="text-[11px] font-medium text-[#334155]">
                          LWD {formatShortDate(item.targetDate)}
                        </span>
                        <StatusBadge status={item.status} showDot={false} />
                      </div>
                      <span className="text-[10px] font-medium text-amber-700">
                        {formatDaysUntil(item.targetDate)} · {item.completionPercent}% cleared
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Row 3: Pending Approvals + Department Task Progress + Recent Activities */}
      <div className="grid gap-5 lg:grid-cols-12">
        <Card className="lg:col-span-4">
          <CardHeader className="pb-3">
            <CardTitle>Pending Approvals</CardTitle>
            <CardDescription>Requests awaiting managerial or HR decision</CardDescription>
          </CardHeader>
          <CardContent>
            {data.pendingApprovals.length === 0 ? (
              <div className="flex flex-col items-center py-6 text-center text-xs text-[#64748B]">
                <CheckCircle2 className="h-5 w-5 text-status-success" />
                <p className="mt-1.5">All approvals are up to date.</p>
              </div>
            ) : (
              <div className="space-y-2.5">
                {data.pendingApprovals.map((app) => (
                  <Link
                    key={app.id}
                    href={app.href}
                    className="block rounded-lg border border-[#E5E7EB] bg-[#F8FAFC]/70 p-3 transition-colors hover:border-brand-border hover:bg-brand-soft/40"
                  >
                    <div className="flex items-center justify-between gap-2">
                      <span className="font-mono text-[11px] font-semibold text-[#111827]">
                        {app.requestNumber}
                      </span>
                      <CompanyPill code={app.companyCode} />
                    </div>
                    <p className="mt-1 text-xs font-medium text-[#111827]">{app.employeeName}</p>
                    <div className="mt-1.5 flex items-center justify-between text-[11px] text-[#64748B]">
                      <span>{app.approvalRole}</span>
                      <span>{formatRelativeTimestamp(app.submittedAt)}</span>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        <Card className="lg:col-span-4">
          <CardHeader className="pb-3">
            <CardTitle>Department Task Progress</CardTitle>
            <CardDescription>Cross-departmental execution across active requests</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {data.departmentTaskProgress.map((dept) => (
              <div key={dept.departmentRole} className="space-y-1.5">
                <div className="flex items-center justify-between text-xs">
                  <span className="font-medium text-[#111827]">{dept.label}</span>
                  <div className="flex items-center gap-2">
                    {dept.overdue > 0 && (
                      <span className="rounded bg-red-50 px-1.5 py-0.5 text-[10px] font-semibold text-red-600">
                        {dept.overdue} overdue
                      </span>
                    )}
                    <span className="font-mono text-[11px] text-[#64748B]">
                      {dept.completed}/{dept.total}
                    </span>
                  </div>
                </div>
                <div className="h-2 w-full overflow-hidden rounded-full bg-[#F1F5F9]">
                  <div
                    className="h-full rounded-full bg-brand transition-all"
                    style={{ width: `${dept.completionRate}%` }}
                  />
                </div>
              </div>
            ))}
          </CardContent>
        </Card>

        <Card className="lg:col-span-4">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
            <div>
              <CardTitle className="flex items-center gap-1.5">
                <Activity className="h-4 w-4 text-brand" />
                Recent Activities
              </CardTitle>
              <CardDescription>Audited lifecycle events</CardDescription>
            </div>
            <Link href="/audit-logs" className="text-xs font-medium text-brand hover:underline">
              Audit trail
            </Link>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {data.recentActivities.map((act) => (
                <div key={act.id} className="flex gap-2.5 text-xs">
                  <div className="mt-1 h-2 w-2 shrink-0 rounded-full bg-brand" />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-1.5">
                      <span className="font-semibold text-[#111827]">{act.actorName}</span>
                      <CompanyPill code={act.companyCode} />
                      <span className="ml-auto text-[10px] text-[#94A3B8]">
                        {formatRelativeTimestamp(act.createdAt)}
                      </span>
                    </div>
                    <p className="mt-0.5 leading-relaxed text-[#64748B]">{act.summary}</p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Row 4: Company Comparison (ECC | NCC | SCII) */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle>Company Comparison — SMC Cement Group</CardTitle>
          <CardDescription>
            Consolidated headcount, active lifecycle requests, and task completion across ECC, NCC, and SCII
          </CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full border-collapse text-left text-xs">
              <thead>
                <tr className="border-y border-[#E5E7EB] bg-[#F8FAFC] text-[11px] font-semibold uppercase tracking-wider text-[#64748B]">
                  <th className="px-5 py-3">Company</th>
                  <th className="px-5 py-3 text-right">Active Employees</th>
                  <th className="px-5 py-3 text-right">Onboarding</th>
                  <th className="px-5 py-3 text-right">Offboarding</th>
                  <th className="px-5 py-3 text-right">Open Tasks</th>
                  <th className="px-5 py-3">Completion Rate</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#F1F5F9]">
                {data.companyComparison.map((comp) => (
                  <tr key={comp.code} className="hover:bg-[#F8FAFC]/80">
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-2.5">
                        <CompanyPill code={comp.code} />
                        <span className="font-medium text-[#111827]">{comp.name}</span>
                      </div>
                    </td>
                    <td className="px-5 py-3.5 text-right font-mono font-medium text-[#111827]">
                      {comp.activeEmployees.toLocaleString("en-US")}
                    </td>
                    <td className="px-5 py-3.5 text-right font-mono text-sky-700">
                      {comp.activeOnboarding}
                    </td>
                    <td className="px-5 py-3.5 text-right font-mono text-amber-700">
                      {comp.activeOffboarding}
                    </td>
                    <td className="px-5 py-3.5 text-right font-mono text-[#475569]">
                      {comp.openTasks}
                    </td>
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-2.5">
                        <div className="h-2 w-28 overflow-hidden rounded-full bg-[#E2E8F0]">
                          <div
                            className="h-full rounded-full bg-status-success"
                            style={{ width: `${comp.completionRate}%` }}
                          />
                        </div>
                        <span className="font-mono text-[11px] font-semibold text-[#111827]">
                          {comp.completionRate}%
                        </span>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
