"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import {
  Target,
  TrendingUp,
  DollarSign,
  FileText,
  Globe,
  Mail,
  Share2,
  Link as LinkIcon,
  RefreshCcw,
} from "lucide-react";
import type {
  Attribution,
  AttributionSource,
} from "@/lib/types/experiments.types";

interface AttributionCardProps {
  className?: string;
}

const sourceIcons: Record<AttributionSource, React.ReactNode> = {
  organic: <Globe className="h-4 w-4" />,
  paid: <DollarSign className="h-4 w-4" />,
  blog: <FileText className="h-4 w-4" />,
  referral: <Share2 className="h-4 w-4" />,
  direct: <LinkIcon className="h-4 w-4" />,
  social: <Share2 className="h-4 w-4" />,
  email: <Mail className="h-4 w-4" />,
};

const sourceColors: Record<AttributionSource, string> = {
  organic: "bg-emerald-500",
  paid: "bg-blue-500",
  blog: "bg-purple-500",
  referral: "bg-amber-500",
  direct: "bg-gray-500",
  social: "bg-pink-500",
  email: "bg-cyan-500",
};

export default function AttributionCard({
  className = "",
}: AttributionCardProps) {
  const [attribution, setAttribution] = useState<Attribution | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [dateRange, setDateRange] = useState<"7d" | "30d" | "90d">("30d");

  const fetchAttribution = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const now = new Date();
      const days = dateRange === "7d" ? 7 : dateRange === "30d" ? 30 : 90;
      const startDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);

      const response = await fetch(
        `/api/staff/analytics/attribution?startDate=${startDate.toISOString()}&endDate=${now.toISOString()}&includeSummary=true`,
      );
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch attribution");
      }

      setAttribution(data.attribution);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, [dateRange]);

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

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(value);
  };

  if (loading) {
    return (
      <div
        className={`rounded-3xl border border-gray-100 bg-white p-6 shadow-lg ${className}`}
      >
        <div className="animate-pulse space-y-4">
          <div className="h-6 w-48 rounded bg-gray-200" />
          <div className="h-32 rounded-xl bg-gray-100" />
          <div className="h-24 rounded-xl bg-gray-100" />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div
        className={`rounded-3xl border border-red-100 bg-red-50 p-6 ${className}`}
      >
        <div className="flex items-center gap-3 text-red-700">
          <Target className="h-5 w-5" />
          <p className="text-sm font-medium">{error}</p>
        </div>
        <button
          onClick={fetchAttribution}
          className="mt-4 text-sm font-medium text-red-700 hover:text-red-800"
        >
          Try again
        </button>
      </div>
    );
  }

  if (!attribution) return null;

  // Sort sources by revenue for display
  const sortedSources = [...attribution.sources].sort(
    (a, b) => b.revenue - a.revenue,
  );
  const topBlogPost = attribution.blogAttribution[0];

  return (
    <div
      className={`flex flex-col rounded-3xl border border-gray-100 bg-white shadow-lg ${className}`}
    >
      {/* Header */}
      <div className="flex items-center justify-between border-b border-gray-100 bg-gradient-to-r from-cyan-50 to-transparent px-6 py-4">
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-cyan-600/10 p-2 text-cyan-600">
            <Target className="h-5 w-5" />
          </div>
          <div>
            <h3 className="text-sm font-semibold text-gray-900">Attribution</h3>
            <p className="text-xs text-gray-500">Track conversion sources</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <select
            value={dateRange}
            onChange={(e) =>
              setDateRange(e.target.value as "7d" | "30d" | "90d")
            }
            className="rounded-lg border border-gray-200 bg-white px-2 py-1 text-xs font-medium text-gray-600 focus:border-cyan-300 focus:outline-none focus:ring-1 focus:ring-cyan-300"
          >
            <option value="7d">7 days</option>
            <option value="30d">30 days</option>
            <option value="90d">90 days</option>
          </select>
          <button
            onClick={fetchAttribution}
            className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
            title="Refresh"
          >
            <RefreshCcw className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Summary Stats */}
      <div className="grid grid-cols-4 gap-4 border-b border-gray-100 px-6 py-4">
        <div className="text-center">
          <p className="text-2xl font-bold text-gray-900">
            {attribution.totals.visitors.toLocaleString()}
          </p>
          <p className="text-xs text-gray-500">Visitors</p>
        </div>
        <div className="text-center">
          <p className="text-2xl font-bold text-gray-900">
            {attribution.totals.demos.toLocaleString()}
          </p>
          <p className="text-xs text-gray-500">Demos</p>
        </div>
        <div className="text-center">
          <p className="text-2xl font-bold text-emerald-600">
            {attribution.totals.overallConversionRate}%
          </p>
          <p className="text-xs text-gray-500">Conv. Rate</p>
        </div>
        <div className="text-center">
          <p className="text-2xl font-bold text-gray-900">
            {formatCurrency(attribution.totals.revenue)}
          </p>
          <p className="text-xs text-gray-500">Revenue</p>
        </div>
      </div>

      {/* Source Breakdown */}
      <div className="flex-1 px-6 py-4">
        <h4 className="mb-3 text-xs font-semibold uppercase tracking-wide text-gray-500">
          Revenue by Source
        </h4>
        <div className="space-y-3">
          {sortedSources.slice(0, 5).map((source) => {
            const percentage =
              attribution.totals.revenue > 0
                ? (source.revenue / attribution.totals.revenue) * 100
                : 0;

            return (
              <div key={source.source} className="space-y-1">
                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-2">
                    <span
                      className={`rounded p-1 text-white ${sourceColors[source.source]}`}
                    >
                      {sourceIcons[source.source]}
                    </span>
                    <span className="font-medium capitalize text-gray-700">
                      {source.source}
                    </span>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className="text-xs text-gray-500">
                      {source.conversionRate}% conv.
                    </span>
                    <span className="tabular-nums font-medium text-gray-900">
                      {formatCurrency(source.revenue)}
                    </span>
                  </div>
                </div>
                <div className="h-2 overflow-hidden rounded-full bg-gray-100">
                  <div
                    className={`h-full rounded-full ${sourceColors[source.source]}`}
                    style={{ width: `${percentage}%` }}
                  />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Top Blog Post */}
      {topBlogPost && (
        <div className="border-t border-gray-100 px-6 py-4">
          <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">
            Top Converting Blog Post
          </h4>
          <div className="rounded-xl bg-purple-50 p-3">
            <div className="flex items-start justify-between">
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium text-purple-900">
                  {topBlogPost.postTitle}
                </p>
                <div className="mt-1 flex items-center gap-3 text-xs text-purple-700">
                  <span>{topBlogPost.views.toLocaleString()} views</span>
                  <span>•</span>
                  <span>{topBlogPost.demos} demos</span>
                  <span>•</span>
                  <span className="flex items-center gap-1">
                    <TrendingUp className="h-3 w-3" />
                    {topBlogPost.conversionRate}%
                  </span>
                </div>
              </div>
              <span className="ml-2 text-sm font-bold text-purple-900">
                {formatCurrency(topBlogPost.revenue)}
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Footer */}
      <div className="border-t border-gray-100 px-6 py-3 text-center">
        <Link
          href="/staff/dashboard/analytics"
          className="text-sm font-medium text-cyan-600 hover:text-cyan-700"
        >
          View full attribution report →
        </Link>
      </div>
    </div>
  );
}
