"use client";

import { useState, useCallback } from "react";
import {
  Eye,
  Users,
  MousePointer,
  TrendingUp,
  Globe,
  Smartphone,
  Monitor,
  Tablet,
  AlertCircle,
  RefreshCw,
} from "lucide-react";

export interface AnalyticsData {
  visits: {
    total: number;
    unique: number;
    today: number;
    week: number;
    month: number;
  };
  conversions: {
    visitorToDemo: number;
    visitorToSignup: number;
    demoToSignup: number;
  };
  topPages: Array<{ page: string; visits: number }>;
  byCountry: Record<string, number>;
  byDevice: Record<string, number>;
}

interface User {
  id: string;
  role: string;
}

export interface AnalyticsDashboardClientProps {
  /**
   * Pre-fetched analytics data from server component.
   */
  initialAnalytics: AnalyticsData | null;
  /**
   * Initial time range used to fetch the data.
   */
  initialTimeRange: string;
  /**
   * Current user info.
   */
  user: User;
}

export default function AnalyticsDashboardClient({
  initialAnalytics,
  initialTimeRange,
  user,
}: AnalyticsDashboardClientProps) {
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(
    initialAnalytics,
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [timeRange, setTimeRange] = useState(initialTimeRange);

  const fetchAnalytics = useCallback(
    async (range?: string) => {
      const targetRange = range || timeRange;
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(
          `/api/staff/dashboard/analytics?timeRange=${targetRange}`,
        );
        if (response.ok) {
          const data = await response.json();
          setAnalytics(data);
        } else {
          const errData = await response.json().catch(() => ({}));
          setError(errData.error || "Failed to fetch analytics data");
        }
      } catch (err) {
        console.error("Failed to fetch analytics:", err);
        setError("Network error. Please try again.");
      } finally {
        setLoading(false);
      }
    },
    [timeRange],
  );

  const handleTimeRangeChange = (range: string) => {
    setTimeRange(range);
    fetchAnalytics(range);
  };

  if (loading && !analytics) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading analytics...</p>
        </div>
      </div>
    );
  }

  if (error && !analytics) {
    return (
      <div className="flex flex-col items-center justify-center h-96 text-center p-6 bg-white rounded-xl shadow-sm border border-gray-200">
        <AlertCircle className="w-12 h-12 text-red-500 mb-4" />
        <h3 className="text-lg font-bold text-gray-900">
          Unable to load analytics
        </h3>
        <p className="text-gray-600 mt-2 max-w-md">{error}</p>
        <button
          onClick={() => fetchAnalytics()}
          className="mt-6 px-6 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700 transition shadow-sm"
        >
          Try Again
        </button>
      </div>
    );
  }

  if (!analytics) {
    return null;
  }

  const getDeviceIcon = (device: string) => {
    switch (device.toLowerCase()) {
      case "mobile":
        return Smartphone;
      case "tablet":
        return Tablet;
      case "desktop":
        return Monitor;
      default:
        return Monitor;
    }
  };

  return (
    <div className="space-y-6">
      {/* Time Range Selector */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex justify-between items-center">
        <div className="flex gap-2">
          {["today", "week", "month"].map((range) => (
            <button
              key={range}
              onClick={() => handleTimeRangeChange(range)}
              disabled={loading}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
                timeRange === range
                  ? "bg-brand-green text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              } ${loading ? "opacity-50 cursor-not-allowed" : ""}`}
            >
              {range.charAt(0).toUpperCase() + range.slice(1)}
            </button>
          ))}
          {loading && (
            <div className="flex items-center ml-2">
              <RefreshCw className="w-4 h-4 animate-spin text-gray-400" />
            </div>
          )}
        </div>
        <div className="text-sm text-gray-500 hidden sm:block">
          Viewing data for{" "}
          <span className="font-semibold text-gray-900">
            {user.role === "SUPER_ADMIN" ? "All Users" : "Your Account"}
          </span>
        </div>
      </div>

      {/* Visit Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-blue-50 rounded-lg">
              <Eye className="w-5 h-5 text-blue-600" />
            </div>
            <p className="text-sm font-medium text-gray-600">Total Visits</p>
          </div>
          <p className="text-3xl font-bold text-brand-ink">
            {analytics.visits.total.toLocaleString()}
          </p>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-green-50 rounded-lg">
              <Users className="w-5 h-5 text-green-600" />
            </div>
            <p className="text-sm font-medium text-gray-600">Unique Visitors</p>
          </div>
          <p className="text-3xl font-bold text-brand-ink">
            {analytics.visits.unique.toLocaleString()}
          </p>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-purple-50 rounded-lg">
              <MousePointer className="w-5 h-5 text-purple-600" />
            </div>
            <p className="text-sm font-medium text-gray-600">Demo Conversion</p>
          </div>
          <p className="text-3xl font-bold text-brand-ink">
            {analytics.conversions.visitorToDemo}%
          </p>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-orange-50 rounded-lg">
              <TrendingUp className="w-5 h-5 text-orange-600" />
            </div>
            <p className="text-sm font-medium text-gray-600">
              Signup Conversion
            </p>
          </div>
          <p className="text-3xl font-bold text-brand-ink">
            {analytics.conversions.visitorToSignup}%
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top Pages */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-brand-ink mb-4">
            Most Visited Pages
          </h3>
          <div className="space-y-3">
            {analytics.topPages.length > 0 ? (
              analytics.topPages.map((page, index) => (
                <div
                  key={page.page}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <span className="flex-shrink-0 flex items-center justify-center w-6 h-6 text-xs font-bold text-white bg-gray-400 rounded-full">
                      {index + 1}
                    </span>
                    <p
                      className="text-sm text-brand-ink font-medium truncate max-w-[200px] sm:max-w-xs"
                      title={page.page}
                    >
                      {page.page}
                    </p>
                  </div>
                  <p className="text-sm font-semibold text-gray-700 flex-shrink-0">
                    {page.visits.toLocaleString()} visits
                  </p>
                </div>
              ))
            ) : (
              <div className="text-center py-10 text-gray-500 text-sm">
                No page data available for this period
              </div>
            )}
          </div>
        </div>

        {/* Conversion Funnel */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-brand-ink mb-4">
            Conversion Funnel
          </h3>
          <div className="space-y-6 py-4">
            <div>
              <div className="flex items-center justify-between mb-2">
                <p className="text-sm font-medium text-gray-700">Visitors</p>
                <p className="text-sm font-bold text-brand-ink">
                  {analytics.visits.unique.toLocaleString()}
                </p>
              </div>
              <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                <div
                  className="h-full bg-blue-500 rounded-full transition-all duration-500"
                  style={{ width: "100%" }}
                ></div>
              </div>
            </div>

            <div className="relative">
              <div className="absolute -top-4 left-1/2 -translate-x-1/2 text-xs text-gray-400 font-medium">
                {"\u2193"} {analytics.conversions.visitorToDemo}%
              </div>
              <div className="flex items-center justify-between mb-2">
                <p className="text-sm font-medium text-gray-700">
                  Demo Requests
                </p>
                <p className="text-sm font-bold text-brand-ink">
                  {Math.round(
                    (analytics.visits.unique *
                      analytics.conversions.visitorToDemo) /
                      100,
                  ).toLocaleString()}
                </p>
              </div>
              <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                <div
                  className="h-full bg-green-500 rounded-full transition-all duration-500"
                  style={{
                    width: `${Math.max(analytics.conversions.visitorToDemo, 2)}%`,
                  }}
                ></div>
              </div>
            </div>

            <div className="relative">
              <div className="absolute -top-4 left-1/2 -translate-x-1/2 text-xs text-gray-400 font-medium">
                {"\u2193"} {analytics.conversions.demoToSignup}% of Demos /{" "}
                {analytics.conversions.visitorToSignup}% of Visitors
              </div>
              <div className="flex items-center justify-between mb-2">
                <p className="text-sm font-medium text-gray-700">Signups</p>
                <p className="text-sm font-bold text-brand-ink">
                  {Math.round(
                    (analytics.visits.unique *
                      analytics.conversions.visitorToSignup) /
                      100,
                  ).toLocaleString()}
                </p>
              </div>
              <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                <div
                  className="h-full bg-purple-500 rounded-full transition-all duration-500"
                  style={{
                    width: `${Math.max(analytics.conversions.visitorToSignup, 1)}%`,
                  }}
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Geographic Distribution */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-brand-ink mb-4">
            Visitors by Country
          </h3>
          {Object.keys(analytics.byCountry).length > 0 ? (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
              {Object.entries(analytics.byCountry).map(([country, count]) => (
                <div
                  key={country}
                  className="text-center p-4 bg-gray-50 rounded-lg hover:bg-blue-50 hover:text-blue-700 transition-colors group"
                >
                  <Globe className="w-6 h-6 text-gray-400 group-hover:text-blue-500 mx-auto mb-2 transition-colors" />
                  <p className="text-xl font-bold text-brand-ink">
                    {count.toLocaleString()}
                  </p>
                  <p
                    className="text-xs text-gray-500 mt-1 truncate"
                    title={country}
                  >
                    {country}
                  </p>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-10 text-gray-500 text-sm">
              No geographic data available
            </div>
          )}
        </div>

        {/* Device Stats */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-brand-ink mb-4">
            Visitors by Device
          </h3>
          {Object.keys(analytics.byDevice).length > 0 ? (
            <div className="grid grid-cols-3 gap-4">
              {Object.entries(analytics.byDevice).map(([device, count]) => {
                const Icon = getDeviceIcon(device);
                return (
                  <div
                    key={device}
                    className="text-center p-4 bg-gray-50 rounded-lg hover:bg-indigo-50 hover:text-indigo-700 transition-colors group"
                  >
                    <Icon className="w-6 h-6 text-gray-400 group-hover:text-indigo-500 mx-auto mb-2 transition-colors" />
                    <p className="text-xl font-bold text-brand-ink">
                      {count.toLocaleString()}
                    </p>
                    <p className="text-xs text-gray-500 mt-1">{device}</p>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-center py-10 text-gray-500 text-sm">
              No device data available
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
