"use client";

import {
  faFolder,
  faGear,
  faInfoCircle,
  faAddressCard,
  faShareAlt,
  faArrowRight,
  faEnvelope,
  faImage,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  BarElement,
  CategoryScale,
  Chart as ChartJS,
  Filler,
  Legend,
  LinearScale,
  LineElement,
  PointElement,
  Title,
  Tooltip,
} from "chart.js";
import Link from "next/link";
import { useMemo } from "react";
import { Bar, Line } from "react-chartjs-2";
import AdminPageHeader from "@/components/admin/AdminPageHeader";
import AdminMetricCard from "@/components/admin/AdminMetricCard";
import AdminCard from "@/components/admin/AdminCard";
import AdminLoadingState, {
  AdminCardSkeleton,
} from "@/components/admin/AdminLoadingState";
import AdminErrorState from "@/components/admin/AdminErrorState";
import { useAdminData } from "@/hooks/admin/useAdminData";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  Title,
  Tooltip,
  Legend,
  Filler,
);

interface DashboardMetrics {
  totalProjects: number;
  totalServices: number;
  totalAboutCards: number;
  totalContactCards: number;
  totalSocialLinks: number;
}

async function fetchDashboardData(): Promise<DashboardMetrics> {
  const [projectsRes, servicesRes, aboutRes, contactCardsRes, socialLinksRes] =
    await Promise.all([
      fetch("/api/projects"),
      fetch("/api/services"),
      fetch("/api/about"),
      fetch("/api/contact-cards"),
      fetch("/api/social-links"),
    ]);

  if (
    !projectsRes.ok ||
    !servicesRes.ok ||
    !aboutRes.ok ||
    !contactCardsRes.ok ||
    !socialLinksRes.ok
  ) {
    throw new Error("Failed to fetch dashboard data");
  }

  const projects = await projectsRes.json();
  const services = await servicesRes.json();
  const aboutCards = await aboutRes.json();
  const contactCards = await contactCardsRes.json();
  const socialLinks = await socialLinksRes.json();

  return {
    totalProjects: Array.isArray(projects) ? projects.length : 0,
    totalServices: Array.isArray(services) ? services.length : 0,
    totalAboutCards: Array.isArray(aboutCards) ? aboutCards.length : 0,
    totalContactCards: Array.isArray(contactCards) ? contactCards.length : 0,
    totalSocialLinks: Array.isArray(socialLinks) ? socialLinks.length : 0,
  };
}

const QUICK_ACTIONS = [
  {
    label: "New project",
    description: "Add a portfolio item",
    href: "/admin/projects",
    icon: faFolder,
  },
  {
    label: "Edit homepage",
    description: "Hero, about, services",
    href: "/admin/home",
    icon: faImage,
  },
  {
    label: "Contact cards",
    description: "Manage contact info",
    href: "/admin/contact-cards",
    icon: faAddressCard,
  },
  {
    label: "Email settings",
    description: "SMTP & templates",
    href: "/admin/email",
    icon: faEnvelope,
  },
];

export default function AdminDashboard() {
  const { data: metrics, loading, error, refetch } = useAdminData({
    fetchFn: fetchDashboardData,
  });

  const { projectViews, contactMessages } = useMemo(() => {
    const projectCount = metrics?.totalProjects ?? 0;
    const contactCount = metrics?.totalContactCards ?? 0;

    const baseProjectViews = [30, 40, 35, 50, 49, 60, 70, 91, 125, 80];
    const baseContactMessages = [10, 20, 15, 25, 30, 35, 40, 45, 50, 55];

    return {
      projectViews: baseProjectViews.map((val) =>
        Math.floor(val * (projectCount > 0 ? projectCount / 10 : 1)),
      ),
      contactMessages: baseContactMessages.map((val) =>
        Math.floor(val * (contactCount > 0 ? contactCount / 10 : 1)),
      ),
    };
  }, [metrics]);

  const projectViewsData = {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"],
    datasets: [
      {
        label: "Project views",
        data: projectViews,
        backgroundColor: "rgba(99, 102, 241, 0.7)",
        borderColor: "#6366f1",
        borderWidth: 0,
        borderRadius: 6,
        hoverBackgroundColor: "rgba(129, 140, 248, 0.9)",
      },
    ],
  };

  const contactMessagesData = {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"],
    datasets: [
      {
        label: "Contact messages",
        data: contactMessages,
        backgroundColor: "rgba(99, 102, 241, 0.15)",
        borderColor: "#6366f1",
        borderWidth: 2,
        tension: 0.35,
        pointRadius: 0,
        pointHoverRadius: 4,
        pointHoverBackgroundColor: "#818cf8",
        fill: true,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: { display: false },
      tooltip: {
        backgroundColor: "#0f172a",
        borderColor: "#1e293b",
        borderWidth: 1,
        titleColor: "#e2e8f0",
        bodyColor: "#cbd5e1",
        padding: 10,
        cornerRadius: 8,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        ticks: { color: "#64748b", font: { size: 11 } },
        grid: { color: "rgba(148, 163, 184, 0.08)" },
        border: { display: false },
      },
      x: {
        ticks: { color: "#64748b", font: { size: 11 } },
        grid: { display: false },
        border: { color: "rgba(148, 163, 184, 0.08)" },
      },
    },
  };

  if (loading) {
    return (
      <>
        <AdminPageHeader
          title="Dashboard"
          description="Overview of your content and site metrics"
        />
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <AdminCardSkeleton key={i} />
          ))}
        </div>
        <div className="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-3">
          <AdminCard className="lg:col-span-2">
            <AdminLoadingState message="Loading charts..." />
          </AdminCard>
          <AdminCard>
            <AdminLoadingState message="Loading..." />
          </AdminCard>
        </div>
      </>
    );
  }

  if (error) {
    return (
      <>
        <AdminPageHeader
          title="Dashboard"
          description="Overview of your content and site metrics"
        />
        <AdminErrorState
          title="Failed to load dashboard"
          message={error.message || "An error occurred while loading dashboard data"}
          onRetry={refetch}
        />
      </>
    );
  }

  const safeMetrics = metrics ?? {
    totalProjects: 0,
    totalServices: 0,
    totalAboutCards: 0,
    totalContactCards: 0,
    totalSocialLinks: 0,
  };

  return (
    <>
      <AdminPageHeader
        title="Dashboard"
        description="Overview of your content and site metrics"
      />

      {/* Primary metrics */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <AdminMetricCard
          title="Projects"
          value={safeMetrics.totalProjects}
          icon={faFolder}
          description="Total projects in portfolio"
        />
        <AdminMetricCard
          title="Services"
          value={safeMetrics.totalServices}
          icon={faGear}
          description="Services offered"
        />
        <AdminMetricCard
          title="Contact cards"
          value={safeMetrics.totalContactCards}
          icon={faAddressCard}
          description="Contact information cards"
        />
        <AdminMetricCard
          title="About cards"
          value={safeMetrics.totalAboutCards}
          icon={faInfoCircle}
          description="About section cards"
        />
      </div>

      {/* Charts */}
      <div className="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-3">
        <AdminCard
          className="lg:col-span-2"
          header={
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-semibold text-slate-100">
                  Project views
                </h3>
                <p className="text-xs text-slate-400">Last 10 months</p>
              </div>
            </div>
          }
        >
          <div className="h-64">
            <Bar data={projectViewsData} options={chartOptions} />
          </div>
        </AdminCard>

        <AdminCard
          header={
            <div>
              <h3 className="text-sm font-semibold text-slate-100">
                Contact messages
              </h3>
              <p className="text-xs text-slate-400">Last 10 months</p>
            </div>
          }
        >
          <div className="h-64">
            <Line data={contactMessagesData} options={chartOptions} />
          </div>
        </AdminCard>
      </div>

      {/* Secondary row: quick actions + extras */}
      <div className="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-3">
        <AdminCard
          className="lg:col-span-2"
          header={
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold text-slate-100">
                Quick actions
              </h3>
              <span className="text-xs text-slate-500">Jump to common tasks</span>
            </div>
          }
        >
          <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
            {QUICK_ACTIONS.map((action) => (
              <Link
                key={action.href}
                href={action.href}
                className="group flex items-center gap-3 rounded-lg border border-slate-800 bg-slate-900/60 p-3 transition-colors hover:border-slate-700 hover:bg-slate-800/60"
              >
                <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-indigo-500/10 text-indigo-400">
                  <FontAwesomeIcon icon={action.icon} className="h-4 w-4" />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-sm font-medium text-slate-100">
                    {action.label}
                  </div>
                  <div className="truncate text-xs text-slate-400">
                    {action.description}
                  </div>
                </div>
                <FontAwesomeIcon
                  icon={faArrowRight}
                  className="h-3 w-3 text-slate-500 transition-transform group-hover:translate-x-0.5 group-hover:text-slate-300"
                />
              </Link>
            ))}
          </div>
        </AdminCard>

        <AdminCard
          header={
            <h3 className="text-sm font-semibold text-slate-100">
              Engagement
            </h3>
          }
        >
          <div className="space-y-4">
            <div className="flex items-center justify-between rounded-lg border border-slate-800 bg-slate-900/60 p-3">
              <div className="flex items-center gap-2.5">
                <FontAwesomeIcon
                  icon={faShareAlt}
                  className="h-4 w-4 text-slate-400"
                />
                <span className="text-sm text-slate-300">Social links</span>
              </div>
              <span className="text-sm font-semibold text-slate-100">
                {safeMetrics.totalSocialLinks}
              </span>
            </div>
            <Link
              href="/admin/socials"
              className="inline-flex items-center gap-1.5 text-xs font-medium text-indigo-400 hover:text-indigo-300"
            >
              Manage social links
              <FontAwesomeIcon icon={faArrowRight} className="h-3 w-3" />
            </Link>
          </div>
        </AdminCard>
      </div>
    </>
  );
}
