"use client";

import { useEffect, useState, useCallback } from "react";
import AdminLayout from "@/components/admin/AdminLayout";
import {
  EyeIcon,
  BarChartIcon,
  MessageIcon,
  FolderIcon,
} from "@/components/Icons";

interface AnalyticsData {
  totalViews: number;
  totalMessages: number;
  topProjects: { id: number; title: string; views: number }[];
  viewsByDay: { date: string; views: number }[];
  messagesByDay: { date: string; count: number }[];
}

export default function AnalyticsPage() {
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState<"7d" | "30d" | "90d">("30d");

  const fetchAnalytics = useCallback(async () => {
    try {
      const res = await fetch(`/api/admin/analytics?period=${period}`);
      if (res.ok) {
        const result = await res.json();
        setData(result);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [period]);

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

  const maxViews = Math.max(...(data?.viewsByDay?.map((d) => d.views) || [1]));

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* 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">Analytics</h1>
            <p className="text-text-muted mt-1">
              Track your portfolio performance
            </p>
          </div>
          <div className="flex gap-1 p-1 bg-surface-elevated rounded-xl">
            {[
              { key: "7d", label: "7 Days" },
              { key: "30d", label: "30 Days" },
              { key: "90d", label: "90 Days" },
            ].map((p) => (
              <button
                key={p.key}
                onClick={() => setPeriod(p.key as typeof period)}
                className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                  period === p.key
                    ? "bg-primary text-white"
                    : "text-text-muted hover:text-text-primary"
                }`}
              >
                {p.label}
              </button>
            ))}
          </div>
        </div>

        {loading ? (
          <div className="py-20 text-center">
            <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full mx-auto" />
          </div>
        ) : (
          <>
            {/* Stats cards */}
            <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
              {[
                {
                  label: "Total Views",
                  value: data?.totalViews || 0,
                  icon: EyeIcon,
                  color: "from-blue-500 to-indigo-600",
                  change: "+12%",
                },
                {
                  label: "Messages",
                  value: data?.totalMessages || 0,
                  icon: MessageIcon,
                  color: "from-green-500 to-emerald-600",
                  change: "+5%",
                },
                {
                  label: "Avg. Views/Day",
                  value: Math.round(
                    (data?.totalViews || 0) / (period === "7d" ? 7 : period === "30d" ? 30 : 90)
                  ),
                  icon: BarChartIcon,
                  color: "from-purple-500 to-pink-600",
                  change: "+8%",
                },
                {
                  label: "Top Projects",
                  value: data?.topProjects?.length || 0,
                  icon: FolderIcon,
                  color: "from-amber-500 to-orange-600",
                  change: "",
                },
              ].map((stat) => {
                const Icon = stat.icon;
                return (
                  <div key={stat.label} className="glass rounded-xl p-6">
                    <div className="flex items-center justify-between mb-4">
                      <div
                        className={`w-10 h-10 rounded-xl bg-gradient-to-br ${stat.color} flex items-center justify-center`}
                      >
                        <Icon size={18} className="text-white" />
                      </div>
                      {stat.change && (
                        <span className="text-xs font-semibold text-success">
                          {stat.change}
                        </span>
                      )}
                    </div>
                    <p className="text-2xl font-bold text-text-primary">
                      {stat.value.toLocaleString()}
                    </p>
                    <p className="text-sm text-text-muted mt-1">{stat.label}</p>
                  </div>
                );
              })}
            </div>

            {/* Charts */}
            <div className="grid lg:grid-cols-2 gap-6">
              {/* Views chart */}
              <div className="glass rounded-xl p-6">
                <h3 className="font-bold text-text-primary mb-6">
                  Views Over Time
                </h3>
                <div className="h-64 flex items-end gap-1">
                  {data?.viewsByDay?.map((day, i) => (
                    <div
                      key={day.date}
                      className="flex-1 flex flex-col items-center gap-1"
                    >
                      <div
                        className="w-full bg-gradient-to-t from-primary to-primary-light rounded-t transition-all hover:opacity-80"
                        style={{
                          height: `${(day.views / maxViews) * 100}%`,
                          minHeight: day.views > 0 ? "4px" : "0",
                        }}
                        title={`${day.date}: ${day.views} views`}
                      />
                      {i % 5 === 0 && (
                        <span className="text-[10px] text-text-muted">
                          {new Date(day.date).toLocaleDateString("en", {
                            month: "short",
                            day: "numeric",
                          })}
                        </span>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              {/* Top projects */}
              <div className="glass rounded-xl p-6">
                <h3 className="font-bold text-text-primary mb-6">
                  Top Performing Projects
                </h3>
                <div className="space-y-4">
                  {data?.topProjects?.map((project, i) => (
                    <div key={project.id} className="flex items-center gap-4">
                      <span className="w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center text-xs font-bold text-primary-light">
                        {i + 1}
                      </span>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-text-primary truncate">
                          {project.title}
                        </p>
                        <div className="h-1.5 bg-surface rounded-full mt-1.5 overflow-hidden">
                          <div
                            className="h-full bg-gradient-to-r from-primary to-accent rounded-full"
                            style={{
                              width: `${
                                (project.views /
                                  (data.topProjects[0]?.views || 1)) *
                                100
                              }%`,
                            }}
                          />
                        </div>
                      </div>
                      <span className="text-sm font-semibold text-text-secondary">
                        {project.views.toLocaleString()}
                      </span>
                    </div>
                  ))}
                  {(!data?.topProjects || data.topProjects.length === 0) && (
                    <p className="text-text-muted text-center py-8">
                      No data yet
                    </p>
                  )}
                </div>
              </div>
            </div>

            {/* Activity summary */}
            <div className="glass rounded-xl p-6">
              <h3 className="font-bold text-text-primary mb-4">
                Quick Insights
              </h3>
              <div className="grid sm:grid-cols-3 gap-4">
                <div className="p-4 bg-surface-elevated rounded-xl">
                  <p className="text-2xl mb-1">📈</p>
                  <p className="text-sm text-text-muted">
                    Your portfolio has received{" "}
                    <span className="font-semibold text-text-primary">
                      {data?.totalViews || 0}
                    </span>{" "}
                    total views
                  </p>
                </div>
                <div className="p-4 bg-surface-elevated rounded-xl">
                  <p className="text-2xl mb-1">💬</p>
                  <p className="text-sm text-text-muted">
                    You&apos;ve received{" "}
                    <span className="font-semibold text-text-primary">
                      {data?.totalMessages || 0}
                    </span>{" "}
                    messages this period
                  </p>
                </div>
                <div className="p-4 bg-surface-elevated rounded-xl">
                  <p className="text-2xl mb-1">🏆</p>
                  <p className="text-sm text-text-muted">
                    Top project:{" "}
                    <span className="font-semibold text-text-primary">
                      {data?.topProjects?.[0]?.title || "N/A"}
                    </span>
                  </p>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </AdminLayout>
  );
}
