"use client";

import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import AdminLayout from "@/components/admin/AdminLayout";
import {
  FolderIcon,
  ImageIcon,
  MessageIcon,
  LayersIcon,
  EyeIcon,
  ArrowRightIcon,
  PlusIcon,
  BarChartIcon,
} from "@/components/Icons";

interface DashboardStats {
  totalProjects: number;
  totalMedia: number;
  totalMessages: number;
  unreadMessages: number;
  totalServices: number;
  totalTestimonials: number;
  totalViews: number;
  categoryBreakdown: { name: string; slug: string; count: number; color: string }[];
  recentProjects: {
    id: number;
    title: string;
    slug: string;
    views: number;
    published: boolean;
    createdAt: string;
  }[];
  recentMessages: {
    id: number;
    name: string;
    email: string;
    subject: string | null;
    read: boolean;
    createdAt: string;
  }[];
}

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/dashboard-stats");
      if (res.ok) {
        const data = await res.json();
        setStats(data);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Page header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-text-primary">Dashboard</h1>
            <p className="text-text-muted mt-1">
              Welcome back! Here&apos;s what&apos;s happening with your portfolio.
            </p>
          </div>
          <Link
            href="/admin/projects/new"
            className="inline-flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-primary to-primary-light text-white font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/25 transition-all text-sm"
          >
            <PlusIcon size={16} />
            New Project
          </Link>
        </div>

        {/* Stats cards */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            {
              label: "Total Projects",
              value: stats?.totalProjects || 0,
              icon: FolderIcon,
              color: "from-blue-500 to-indigo-600",
              href: "/admin/projects",
            },
            {
              label: "Media Files",
              value: stats?.totalMedia || 0,
              icon: ImageIcon,
              color: "from-purple-500 to-pink-600",
              href: "/admin/media",
            },
            {
              label: "Messages",
              value: stats?.totalMessages || 0,
              badge: stats?.unreadMessages || 0,
              icon: MessageIcon,
              color: "from-green-500 to-emerald-600",
              href: "/admin/messages",
            },
            {
              label: "Total Views",
              value: stats?.totalViews || 0,
              icon: EyeIcon,
              color: "from-amber-500 to-orange-600",
              href: "/admin/analytics",
            },
          ].map((stat) => {
            const Icon = stat.icon;
            return (
              <Link
                key={stat.label}
                href={stat.href}
                className="glass rounded-xl p-6 card-hover group"
              >
                <div className="flex items-start justify-between mb-4">
                  <div
                    className={`w-12 h-12 rounded-xl bg-gradient-to-br ${stat.color} flex items-center justify-center group-hover:scale-110 transition-transform`}
                  >
                    <Icon size={22} className="text-white" />
                  </div>
                  {stat.badge !== undefined && stat.badge > 0 && (
                    <span className="px-2 py-0.5 text-xs font-bold bg-danger text-white rounded-full">
                      {stat.badge} new
                    </span>
                  )}
                </div>
                <p className="text-3xl font-bold text-text-primary">
                  {stat.value.toLocaleString()}
                </p>
                <p className="text-sm text-text-muted mt-1">{stat.label}</p>
              </Link>
            );
          })}
        </div>

        {/* Two column layout */}
        <div className="grid lg:grid-cols-3 gap-6">
          {/* Category breakdown */}
          <div className="lg:col-span-1 glass rounded-xl p-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-lg font-bold text-text-primary">
                Projects by Category
              </h2>
              <BarChartIcon size={20} className="text-text-muted" />
            </div>
            <div className="space-y-4">
              {stats?.categoryBreakdown?.map((cat) => (
                <div key={cat.slug}>
                  <div className="flex items-center justify-between mb-1.5">
                    <span className="text-sm text-text-secondary">{cat.name}</span>
                    <span className="text-sm font-semibold text-text-primary">
                      {cat.count}
                    </span>
                  </div>
                  <div className="h-2 bg-surface rounded-full overflow-hidden">
                    <div
                      className="h-full rounded-full transition-all duration-500"
                      style={{
                        width: `${
                          stats.totalProjects > 0
                            ? (cat.count / stats.totalProjects) * 100
                            : 0
                        }%`,
                        backgroundColor: cat.color || "#6366f1",
                      }}
                    />
                  </div>
                </div>
              ))}
              {(!stats?.categoryBreakdown || stats.categoryBreakdown.length === 0) && (
                <p className="text-sm text-text-muted text-center py-8">
                  No projects yet
                </p>
              )}
            </div>
          </div>

          {/* Recent projects */}
          <div className="lg:col-span-2 glass rounded-xl p-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-lg font-bold text-text-primary">
                Recent Projects
              </h2>
              <Link
                href="/admin/projects"
                className="text-sm text-primary-light hover:text-accent transition-colors flex items-center gap-1"
              >
                View all <ArrowRightIcon size={14} />
              </Link>
            </div>
            <div className="space-y-3">
              {stats?.recentProjects?.map((project) => (
                <Link
                  key={project.id}
                  href={`/admin/projects/${project.id}`}
                  className="flex items-center gap-4 p-4 rounded-xl bg-surface hover:bg-surface-hover transition-colors"
                >
                  <div className="w-12 h-12 rounded-lg bg-gradient-to-br from-primary/20 to-accent/20 flex items-center justify-center text-2xl">
                    📁
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-text-primary truncate">
                      {project.title}
                    </h3>
                    <p className="text-sm text-text-muted">
                      {new Date(project.createdAt).toLocaleDateString()}
                    </p>
                  </div>
                  <div className="text-right shrink-0">
                    <p className="text-sm font-semibold text-text-primary">
                      {project.views} views
                    </p>
                    <span
                      className={`inline-block px-2 py-0.5 text-[10px] rounded-full ${
                        project.published
                          ? "bg-success/10 text-success"
                          : "bg-warning/10 text-warning"
                      }`}
                    >
                      {project.published ? "Published" : "Draft"}
                    </span>
                  </div>
                </Link>
              ))}
              {(!stats?.recentProjects || stats.recentProjects.length === 0) && (
                <div className="text-center py-12">
                  <FolderIcon size={40} className="text-text-muted mx-auto mb-3" />
                  <p className="text-text-muted">No projects yet</p>
                  <Link
                    href="/admin/projects/new"
                    className="inline-flex items-center gap-1 mt-3 text-sm text-primary-light hover:text-accent"
                  >
                    <PlusIcon size={14} /> Create your first project
                  </Link>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Recent messages */}
        <div className="glass rounded-xl p-6">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-lg font-bold text-text-primary">
              Recent Messages
            </h2>
            <Link
              href="/admin/messages"
              className="text-sm text-primary-light hover:text-accent transition-colors flex items-center gap-1"
            >
              View all <ArrowRightIcon size={14} />
            </Link>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border">
                  <th className="text-left py-3 px-4 text-xs font-semibold text-text-muted uppercase tracking-wider">
                    Sender
                  </th>
                  <th className="text-left py-3 px-4 text-xs font-semibold text-text-muted uppercase tracking-wider">
                    Subject
                  </th>
                  <th className="text-left py-3 px-4 text-xs font-semibold text-text-muted uppercase tracking-wider">
                    Date
                  </th>
                  <th className="text-left py-3 px-4 text-xs font-semibold text-text-muted uppercase tracking-wider">
                    Status
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {stats?.recentMessages?.map((msg) => (
                  <tr
                    key={msg.id}
                    className="hover:bg-surface-hover transition-colors"
                  >
                    <td className="py-3 px-4">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-full bg-gradient-to-br from-primary to-accent flex items-center justify-center text-white text-sm font-bold">
                          {msg.name.charAt(0).toUpperCase()}
                        </div>
                        <div>
                          <p className="font-medium text-text-primary text-sm">
                            {msg.name}
                          </p>
                          <p className="text-xs text-text-muted">{msg.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="py-3 px-4">
                      <p className="text-sm text-text-secondary truncate max-w-[200px]">
                        {msg.subject || "No subject"}
                      </p>
                    </td>
                    <td className="py-3 px-4">
                      <p className="text-sm text-text-muted">
                        {new Date(msg.createdAt).toLocaleDateString()}
                      </p>
                    </td>
                    <td className="py-3 px-4">
                      <span
                        className={`inline-block px-2 py-0.5 text-[10px] rounded-full ${
                          msg.read
                            ? "bg-text-muted/10 text-text-muted"
                            : "bg-primary/10 text-primary-light font-semibold"
                        }`}
                      >
                        {msg.read ? "Read" : "Unread"}
                      </span>
                    </td>
                  </tr>
                ))}
                {(!stats?.recentMessages || stats.recentMessages.length === 0) && (
                  <tr>
                    <td colSpan={4} className="py-12 text-center">
                      <MessageIcon size={40} className="text-text-muted mx-auto mb-3" />
                      <p className="text-text-muted">No messages yet</p>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Quick actions */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: "Add Project", href: "/admin/projects/new", icon: "📁", color: "from-blue-500/10 to-indigo-500/10" },
            { label: "Upload Media", href: "/admin/media/upload", icon: "📷", color: "from-purple-500/10 to-pink-500/10" },
            { label: "Add Service", href: "/admin/services", icon: "⚡", color: "from-amber-500/10 to-orange-500/10" },
            { label: "View Analytics", href: "/admin/analytics", icon: "📊", color: "from-green-500/10 to-emerald-500/10" },
          ].map((action) => (
            <Link
              key={action.label}
              href={action.href}
              className={`glass rounded-xl p-5 card-hover bg-gradient-to-br ${action.color} flex items-center gap-4`}
            >
              <span className="text-3xl">{action.icon}</span>
              <span className="font-semibold text-text-primary">{action.label}</span>
            </Link>
          ))}
        </div>
      </div>
    </AdminLayout>
  );
}
