"use client";

import React from "react";

import {
  Users,
  UserCog,
  Briefcase,
  CheckCircle2,
  Clock,
  FileText,
  ArrowRight,
  AlertCircle,
} from "lucide-react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
  PieChart,
  Pie,
  Legend,
} from "recharts";
import {
  useAdminDashboardStats,
  useAdminPendingTasks,
  useAdminRejectedTasks,
} from "../hooks/dashboard.hooks";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { CATEGORY_PALETTE } from "@/lib/chart-colors";
import { useRouter } from "next/navigation";
import { getStatusVariant } from "@/lib/status-variant";
import { useTaskSocket } from "@/hooks/useTaskSocket";
import { useAppSelector } from "@/lib/store";

// ── Colour tokens ─────────────────────────────────────────────
const INK = "#1B2A41";
const BRASS = "#B8860B";
const GREEN = "#2F6B4F";
const RUST = "#A63D40";
const SLATE = "#5C6B7A";
const PAPER = "#F6F3EC";
const LINE = "#E2DDD3";

const STATUS_COLORS: Record<string, string> = {
  PENDING: "#F59E0B",
  IN_PROGRESS: "#3B82F6",
  EMPLOYEE_DONE: "#8B5CF6",
  MANAGER_APPROVAL: "#06B6D4",
  CLIENT_APPROVAL: "#F97316",
  FILING_PENDING: "#EF4444",
  COMPLETED: "#10B981",
  REJECTED: "#DC2626",
};

const CLIENT_COLORS: Record<string, string> = {
  ACTIVE: "#10B981",
  INVITED: "#F59E0B",
  INACTIVE: "#EF4444",
};

const DEPT_COLORS = [
  "#3B82F6",
  "#10B981",
  "#F59E0B",
  "#8B5CF6",
  "#EF4444",
  "#06B6D4",
  "#F97316",
  "#1B2A41",
];

function StatCard({
  title,
  value,
  icon: Icon,
  color = INK,
}: {
  title: string;
  value: number | string;
  icon: React.ElementType;
  color?: string;
}) {
  return (
    <div
      style={{
        background: "#fff",
        border: `1px solid ${LINE}`,
        borderTop: `3px solid ${color}`,
        borderRadius: 4,
        padding: "16px 18px",
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
        }}
      >
        <span
          style={{
            fontSize: 10,
            textTransform: "uppercase",
            letterSpacing: "0.07em",
            color: SLATE,
            fontWeight: 600,
          }}
        >
          {title}
        </span>
        <Icon size={15} color={color} style={{ opacity: 0.8 }} />
      </div>
      <div
        style={{
          fontFamily: "'Lora', Georgia, serif",
          fontSize: 28,
          fontWeight: 700,
          color: INK,
          marginTop: 8,
        }}
      >
        {value}
      </div>
    </div>
  );
}

function SkeletonCard() {
  return (
    <div
      style={{
        background: "#fff",
        border: `1px solid ${LINE}`,
        borderTop: `3px solid ${LINE}`,
        borderRadius: 4,
        padding: "16px 18px",
        animation: "tf-shimmer 1.4s infinite",
      }}
    >
      <div
        style={{
          height: 10,
          background: LINE,
          borderRadius: 4,
          width: "60%",
          marginBottom: 12,
        }}
      />
      <div
        style={{ height: 28, background: LINE, borderRadius: 4, width: "40%" }}
      />
    </div>
  );
}

function ChartTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null;
  return (
    <div className="rounded-md border border-border bg-card px-3 py-2 text-xs shadow-sm">
      {label && <div className="text-muted-foreground mb-0.5">{label}</div>}
      <div className="font-bold text-foreground">
        {payload[0].name ? `${payload[0].name}: ` : ""}
        {payload[0].value}
      </div>
    </div>
  );
}

export function AdminDashboard() {
  const router = useRouter();
  const orgId = useAppSelector((s) => s.auth.user?.organizationId);
  useTaskSocket(orgId, [
    "admin-dashboard-stats",
    "admin-pending-tasks",
    "admin-rejected-tasks",
    "admin-tasks",
  ]);
  const { data, isLoading } = useAdminDashboardStats();
  const { data: pendingTasks = [], isLoading: pendingLoading } =
    useAdminPendingTasks();
  const { data: rejectedTasks = [], isLoading: rejectedLoading } =
    useAdminRejectedTasks();
  const [taskTab, setTaskTab] = React.useState<"pending" | "rejected">(
    "pending"
  );

  const cards = data?.cards;
  const taskStatusGraph = data?.taskStatusGraph ?? [];
  const departmentTaskGraph = data?.departmentTaskGraph ?? [];
  const clientStatusGraph = data?.clientStatusGraph ?? [];

  const statCards = [
    {
      title: "Total Clients",
      value: cards?.totalClients ?? 0,
      icon: Users,
      color: INK,
    },
    {
      title: "Total Employees",
      value: cards?.totalEmployees ?? 0,
      icon: Briefcase,
      color: GREEN,
    },
    {
      title: "Total Managers",
      value: cards?.totalManagers ?? 0,
      icon: UserCog,
      color: BRASS,
    },
    {
      title: "Total Tasks",
      value: cards?.totalTasks ?? 0,
      icon: FileText,
      color: SLATE,
    },
    {
      title: "Pending Tasks",
      value: cards?.pendingTasks ?? 0,
      icon: Clock,
      color: RUST,
    },
    {
      title: "Completed Tasks",
      value: cards?.completedTasks ?? 0,
      icon: CheckCircle2,
      color: GREEN,
    },
  ];

  return (
    <div style={{ fontFamily: "'IBM Plex Sans', sans-serif" }}>
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Lora:wght@500;700&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;600&display=swap');
        @keyframes tf-shimmer { 0%,100%{opacity:1} 50%{opacity:0.5} }
        .tf-card-head {
          padding: 14px 18px;
          border-bottom: 1px solid ${LINE};
          background: ${PAPER};
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .tf-card-title {
          font-family: 'Lora', serif;
          font-weight: 700;
          font-size: 14px;
          color: ${INK};
          display: flex;
          align-items: center;
          gap: 7px;
        }
        .tf-card-desc { font-size: 11px; color: ${SLATE}; margin-top: 2px; }
      `}</style>

      {/* Header */}
      <div style={{ marginBottom: 22 }}>
        <h1
          style={{
            fontFamily: "'Lora', serif",
            fontSize: 26,
            fontWeight: 700,
            color: INK,
            margin: 0,
          }}
        >
          Dashboard
        </h1>
        <p style={{ fontSize: 13, color: SLATE, marginTop: 4 }}>
          Organisation overview — clients, team & tasks
        </p>
      </div>

      {/* Stat Cards */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))",
          gap: 14,
        }}
      >
        {isLoading
          ? Array.from({ length: 6 }).map((_, i) => <SkeletonCard key={i} />)
          : statCards.map((s) => (
              <StatCard
                key={s.title}
                title={s.title}
                value={s.value}
                icon={s.icon}
                color={s.color}
              />
            ))}
      </div>

      {/* Row 2: Task Status + Client Status — 2 separate cards */}
      <div className="mt-3 grid grid-cols-2 gap-6">
        {/* Task Status Breakdown */}
        <Card>
          <div className="flex items-center gap-2 px-5 py-3.5 border-b">
            <FileText className="h-4 w-4 text-muted-foreground" />
            <CardTitle className="text-sm font-semibold">
              Task Status Breakdown
            </CardTitle>
          </div>
          <div className="p-6">
            {taskStatusGraph.filter((d) => d.count > 0).length === 0 ? (
              <div className="h-60 flex items-center justify-center text-sm text-muted-foreground">
                No task data yet
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={260}>
                <BarChart
                  layout="vertical"
                  data={taskStatusGraph.filter((d) => d.count > 0)}
                  margin={{ top: 4, right: 24, left: 10, bottom: 4 }}
                  barSize={14}
                >
                  <CartesianGrid
                    strokeDasharray="2 4"
                    className="stroke-border"
                    horizontal={false}
                  />
                  <XAxis
                    type="number"
                    tick={{ fontSize: 10 }}
                    className="fill-muted-foreground"
                    axisLine={false}
                    tickLine={false}
                    allowDecimals={false}
                  />
                  <YAxis
                    type="category"
                    dataKey="status"
                    tick={{ fontSize: 10 }}
                    className="fill-muted-foreground"
                    axisLine={false}
                    tickLine={false}
                    width={115}
                  />
                  <Tooltip
                    content={<ChartTooltip />}
                    cursor={{ fill: "hsl(var(--muted))" }}
                  />
                  <Bar dataKey="count" radius={[0, 5, 5, 0]}>
                    {taskStatusGraph.map((entry) => (
                      <Cell
                        key={entry.status}
                        fill={STATUS_COLORS[entry.status] ?? "#64748B"}
                      />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            )}
          </div>
        </Card>

        {/* Client Status */}
        <Card>
          <div className="flex items-center gap-2 px-5 py-3.5 border-b">
            <Users className="h-4 w-4 text-muted-foreground" />
            <CardTitle className="text-sm font-semibold">
              Client Status
            </CardTitle>
          </div>
          <div className="p-6 flex flex-col">
            {clientStatusGraph.length === 0 ? (
              <div className="h-60 flex items-center justify-center text-sm text-muted-foreground">
                No client data yet
              </div>
            ) : (
              <>
                <ResponsiveContainer width="100%" height={200}>
                  <PieChart>
                    <Pie
                      data={clientStatusGraph}
                      dataKey="count"
                      nameKey="status"
                      cx="50%"
                      cy="50%"
                      innerRadius={55}
                      outerRadius={82}
                      paddingAngle={3}
                      stroke="none"
                    >
                      {clientStatusGraph.map((entry) => (
                        <Cell
                          key={entry.status}
                          fill={CLIENT_COLORS[entry.status] ?? "#64748B"}
                        />
                      ))}
                    </Pie>
                    <Tooltip content={<ChartTooltip />} />
                  </PieChart>
                </ResponsiveContainer>
                <div className="mt-4 space-y-3">
                  {clientStatusGraph.map((entry) => (
                    <div
                      key={entry.status}
                      className="flex items-center justify-between text-sm"
                    >
                      <div className="flex items-center gap-2">
                        <span
                          className="w-2.5 h-2.5 rounded-full"
                          style={{
                            background:
                              CLIENT_COLORS[entry.status] ?? "#64748B",
                          }}
                        />
                        <span className="text-muted-foreground">
                          {entry.status}
                        </span>
                      </div>
                      <span className="font-semibold tabular-nums">
                        {entry.count}
                      </span>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </Card>
      </div>

      {/* Row 3: Department Workload + Pending Tasks — 2 separate cards */}
      <div className="mt-3 mb-6 grid grid-cols-2 gap-6">
        {/* Department Workload */}
        <Card>
          <div className="flex items-center gap-2 px-5 py-3.5 border-b">
            <Briefcase className="h-4 w-4 text-muted-foreground" />
            <CardTitle className="text-sm font-semibold">
              Department Workload
            </CardTitle>
          </div>
          <div className="p-6">
            {departmentTaskGraph.length === 0 ? (
              <div className="h-60 flex items-center justify-center text-sm text-muted-foreground">
                No department data yet
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={280}>
                <PieChart>
                  <Pie
                    data={departmentTaskGraph}
                    dataKey="tasks"
                    nameKey="department"
                    cx="50%"
                    cy="45%"
                    innerRadius={60}
                    outerRadius={95}
                    paddingAngle={3}
                    stroke="none"
                  >
                    {departmentTaskGraph.map((_, i) => (
                      <Cell
                        key={i}
                        fill={CATEGORY_PALETTE[i % CATEGORY_PALETTE.length]}
                      />
                    ))}
                  </Pie>
                  <Tooltip content={<ChartTooltip />} />
                  <Legend
                    iconType="circle"
                    iconSize={8}
                    wrapperStyle={{ fontSize: 11 }}
                  />
                </PieChart>
              </ResponsiveContainer>
            )}
          </div>
        </Card>

        {/* Pending / Rejected Tasks */}
        <Card>
          <div className="flex items-center justify-between px-5 py-3.5 border-b">
            <div className="flex items-center gap-3">
              <AlertCircle className="h-4 w-4 text-amber-500" />
              <div className="flex gap-1 bg-muted rounded-md p-0.5">
                <button
                  onClick={() => setTaskTab("pending")}
                  className={`text-xs px-3 py-1 rounded transition-colors font-medium ${
                    taskTab === "pending"
                      ? "bg-background shadow text-foreground"
                      : "text-muted-foreground hover:text-foreground"
                  }`}
                >
                  Pending
                </button>
                <button
                  onClick={() => setTaskTab("rejected")}
                  className={`text-xs px-3 py-1 rounded transition-colors font-medium ${
                    taskTab === "rejected"
                      ? "bg-background shadow text-foreground"
                      : "text-muted-foreground hover:text-foreground"
                  }`}
                >
                  Rejected
                </button>
              </div>
            </div>
            <button
              onClick={() => router.push("/admin/tasks")}
              className="flex items-center gap-1 text-xs text-primary hover:underline"
            >
              View All <ArrowRight className="h-3 w-3" />
            </button>
          </div>
          {(taskTab === "pending" ? pendingLoading : rejectedLoading) ? (
            <div className="p-4 space-y-2">
              {[1, 2, 3].map((i) => (
                <div
                  key={i}
                  className="h-12 bg-muted animate-pulse rounded-lg"
                />
              ))}
            </div>
          ) : (taskTab === "pending" ? pendingTasks : rejectedTasks).length ===
            0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <CheckCircle2 className="h-8 w-8 text-emerald-500/40 mb-2" />
              <p className="text-sm text-muted-foreground">
                No {taskTab} tasks
              </p>
            </div>
          ) : (
            <div className="divide-y divide-border">
              {(taskTab === "pending" ? pendingTasks : rejectedTasks).map(
                (task) => (
                  <div
                    key={task.id}
                    onClick={() => router.push(`/admin/tasks/${task.id}`)}
                    className="flex items-center gap-3 px-4 py-3.5 hover:bg-muted/40 cursor-pointer transition-colors"
                  >
                    <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                      <span className="text-[10px] font-bold text-primary">
                        {task.title.slice(0, 2).toUpperCase()}
                      </span>
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs font-semibold truncate">
                        {task.title}
                      </p>
                      <p className="text-[10px] text-muted-foreground truncate">
                        {task.client.name} · {task.service.name}
                        {task.assignedEmployee &&
                          ` · ${task.assignedEmployee.name}`}
                      </p>
                    </div>
                    <div className="flex flex-col items-end gap-1 shrink-0">
                      <span
                        className="text-[10px] font-semibold px-1.5 py-0.5 rounded border"
                        style={{
                          color: STATUS_COLORS[task.status] ?? "#64748B",
                          backgroundColor: `${
                            STATUS_COLORS[task.status] ?? "#64748B"
                          }18`,
                          borderColor: `${
                            STATUS_COLORS[task.status] ?? "#64748B"
                          }35`,
                        }}
                      >
                        {task.status.replace(/_/g, " ")}
                      </span>
                      {task.dueDate && (
                        <span className="text-[10px] text-muted-foreground">
                          {new Date(task.dueDate).toLocaleDateString("en-IN", {
                            day: "2-digit",
                            month: "short",
                            year: "numeric",
                          })}
                        </span>
                      )}
                    </div>
                  </div>
                )
              )}
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}
