"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Calendar,
  AlertTriangle,
  RefreshCw,
  CreditCard,
  AlertCircle,
  Clock,
  DollarSign,
  Mail,
  UserMinus,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface RenewalInfo {
  userId: string;
  name: string | null;
  companyName: string | null;
  email: string;
  renewalDate: string;
  daysUntilRenewal: number;
  tier: string | null;
  billingPeriod: string | null;
  healthScore: number;
  healthStatus: "healthy" | "at_risk" | "critical";
  renewalRisk: "low" | "medium" | "high" | "critical";
  mrrAtRisk: number;
  paymentFailures: number;
  isDunning: boolean;
}

interface DunningInfo {
  userId: string;
  name: string | null;
  email: string;
  failureCount: number;
  lastAttempt: string | null;
  nextRetry: string | null;
  amount: number;
}

interface ChurnedAccount {
  userId: string;
  name: string | null;
  companyName: string | null;
  email: string;
  churnedAt: string;
  previousTier: string | null;
  lostMrr: number;
  churnReason: string | null;
  lifetimeDays: number;
}

interface RenewalsData {
  next30Days: RenewalInfo[];
  next60Days: RenewalInfo[];
  next90Days: RenewalInfo[];
  dunning: DunningInfo[];
  churned30Days: ChurnedAccount[];
  totalRevenueAtRisk: number;
  summary: {
    totalUpcoming: number;
    highRiskCount: number;
    dunningCount: number;
    churnedCount: number;
  };
}

// Risk level styling
function getRiskBadgeColor(level: string): string {
  switch (level) {
    case "low":
      return "bg-emerald-100 text-emerald-700";
    case "medium":
      return "bg-amber-100 text-amber-700";
    case "high":
      return "bg-orange-100 text-orange-700";
    case "critical":
      return "bg-red-100 text-red-700";
    default:
      return "bg-gray-100 text-gray-700";
  }
}

// Days until renewal badge
function getDaysColor(days: number): string {
  if (days <= 7) return "text-red-600 bg-red-50";
  if (days <= 14) return "text-orange-600 bg-orange-50";
  if (days <= 30) return "text-amber-600 bg-amber-50";
  return "text-gray-600 bg-gray-50";
}

// Loading skeleton
function RenewalsSkeleton() {
  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6">
      <div className="flex items-center justify-between mb-6">
        <Skeleton className="h-6 w-48" />
        <Skeleton className="h-8 w-8 rounded-full" />
      </div>
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="p-4 rounded-lg bg-gray-50">
            <Skeleton className="h-8 w-16 mb-2" />
            <Skeleton className="h-4 w-24" />
          </div>
        ))}
      </div>
      <div className="space-y-3">
        {[...Array(5)].map((_, i) => (
          <Skeleton key={i} className="h-16 w-full" />
        ))}
      </div>
    </div>
  );
}

// Error state component
function ErrorState({
  message,
  onRetry,
}: {
  message: string;
  onRetry: () => void;
}) {
  return (
    <div className="rounded-2xl border border-red-100 bg-red-50 p-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-red-100 p-2">
            <AlertTriangle className="h-5 w-5 text-red-600" />
          </div>
          <div>
            <p className="font-medium text-red-900">
              Failed to load renewals data
            </p>
            <p className="text-sm text-red-700">{message}</p>
          </div>
        </div>
        <button
          onClick={onRetry}
          className="flex items-center gap-2 rounded-lg bg-red-100 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-200 transition-colors"
        >
          <RefreshCw className="h-4 w-4" />
          Retry
        </button>
      </div>
    </div>
  );
}

// Tab selector component
type Tab = "upcoming" | "dunning" | "churned";

function TabSelector({
  activeTab,
  onTabChange,
  counts,
}: {
  activeTab: Tab;
  onTabChange: (tab: Tab) => void;
  counts: { upcoming: number; dunning: number; churned: number };
}) {
  const tabs: {
    id: Tab;
    label: string;
    icon: React.ReactNode;
    count: number;
  }[] = [
    {
      id: "upcoming",
      label: "Upcoming",
      icon: <Calendar className="h-4 w-4" />,
      count: counts.upcoming,
    },
    {
      id: "dunning",
      label: "Dunning",
      icon: <CreditCard className="h-4 w-4" />,
      count: counts.dunning,
    },
    {
      id: "churned",
      label: "Churned",
      icon: <UserMinus className="h-4 w-4" />,
      count: counts.churned,
    },
  ];

  return (
    <div className="flex gap-1 p-1 rounded-lg bg-gray-100">
      {tabs.map((tab) => (
        <button
          key={tab.id}
          onClick={() => onTabChange(tab.id)}
          className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
            activeTab === tab.id
              ? "bg-white text-gray-900 shadow-sm"
              : "text-gray-600 hover:text-gray-900"
          }`}
        >
          {tab.icon}
          {tab.label}
          {tab.count > 0 && (
            <span
              className={`px-1.5 py-0.5 rounded-full text-xs ${
                activeTab === tab.id ? "bg-gray-100" : "bg-gray-200"
              }`}
            >
              {tab.count}
            </span>
          )}
        </button>
      ))}
    </div>
  );
}

export default function RenewalsCard() {
  const [data, setData] = useState<RenewalsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>("upcoming");
  const [sendingReminder, setSendingReminder] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/staff/analytics/renewals");
      if (!response.ok) {
        throw new Error("Failed to fetch renewals data");
      }
      const result = await response.json();
      if (result.success) {
        setData(result.data);
      } else {
        throw new Error(result.error || "Unknown error");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const handleSendReminder = async (userId: string) => {
    setSendingReminder(userId);
    try {
      // TODO: Implement actual reminder API call
      await new Promise((resolve) => setTimeout(resolve, 1000));
      console.log(`Sent reminder to ${userId}`);
    } catch (err) {
      console.error("Failed to send reminder:", err);
    } finally {
      setSendingReminder(null);
    }
  };

  if (loading) return <RenewalsSkeleton />;
  if (error) return <ErrorState message={error} onRetry={fetchData} />;
  if (!data) return null;

  const allUpcoming = [
    ...data.next30Days,
    ...data.next60Days,
    ...data.next90Days,
  ];

  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm hover:shadow-lg transition-shadow">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="rounded-xl bg-indigo-100 p-3">
            <Calendar className="h-6 w-6 text-indigo-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Renewals & Dunning
            </h3>
            <p className="text-xs text-gray-500">
              {data.summary.totalUpcoming} upcoming renewals
            </p>
          </div>
        </div>
        <button
          onClick={fetchData}
          disabled={loading}
          className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors disabled:opacity-50"
          title="Refresh data"
        >
          <RefreshCw className={`h-5 w-5 ${loading ? "animate-spin" : ""}`} />
        </button>
      </div>

      {/* Summary stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <div className="p-4 rounded-lg bg-indigo-50 text-center">
          <p className="text-2xl font-bold text-indigo-600">
            {data.summary.totalUpcoming}
          </p>
          <p className="text-xs text-indigo-600/70">Upcoming</p>
        </div>
        <div className="p-4 rounded-lg bg-orange-50 text-center">
          <p className="text-2xl font-bold text-orange-600">
            {data.summary.highRiskCount}
          </p>
          <p className="text-xs text-orange-600/70">High Risk</p>
        </div>
        <div className="p-4 rounded-lg bg-red-50 text-center">
          <p className="text-2xl font-bold text-red-600">
            {data.summary.dunningCount}
          </p>
          <p className="text-xs text-red-600/70">In Dunning</p>
        </div>
        <div className="p-4 rounded-lg bg-amber-50 text-center">
          <div className="flex items-center justify-center gap-1">
            <DollarSign className="h-4 w-4 text-amber-600" />
            <p className="text-lg font-bold text-amber-600">
              {data.totalRevenueAtRisk.toLocaleString()}
            </p>
          </div>
          <p className="text-xs text-amber-600/70">At Risk</p>
        </div>
      </div>

      {/* Tab selector */}
      <TabSelector
        activeTab={activeTab}
        onTabChange={setActiveTab}
        counts={{
          upcoming: allUpcoming.length,
          dunning: data.dunning.length,
          churned: data.churned30Days.length,
        }}
      />

      {/* Tab content */}
      <div className="mt-4 space-y-3 max-h-[400px] overflow-y-auto">
        {activeTab === "upcoming" && (
          <>
            {allUpcoming.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <Calendar className="h-8 w-8 mx-auto mb-2 text-gray-300" />
                <p>No upcoming renewals</p>
              </div>
            ) : (
              allUpcoming.map((renewal) => (
                <div
                  key={renewal.userId}
                  className="flex items-center justify-between p-4 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors"
                >
                  <div className="flex items-center gap-4">
                    <div
                      className={`px-3 py-1.5 rounded-lg text-xs font-medium ${getDaysColor(renewal.daysUntilRenewal)}`}
                    >
                      <Clock className="h-3 w-3 inline-block mr-1" />
                      {renewal.daysUntilRenewal}d
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">
                        {renewal.companyName || renewal.name || "Unknown"}
                      </p>
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <span>{renewal.email}</span>
                        {renewal.tier && <span>| {renewal.tier}</span>}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    {renewal.isDunning && (
                      <span title="In dunning">
                        <AlertCircle className="h-4 w-4 text-red-500" />
                      </span>
                    )}
                    <span
                      className={`px-2 py-0.5 rounded-full text-xs font-medium ${getRiskBadgeColor(renewal.renewalRisk)}`}
                    >
                      {renewal.renewalRisk}
                    </span>
                    <span className="text-sm font-medium text-gray-600">
                      ${renewal.mrrAtRisk}
                    </span>
                    <button
                      onClick={() => handleSendReminder(renewal.userId)}
                      disabled={sendingReminder === renewal.userId}
                      className="p-2 rounded-lg text-indigo-600 hover:bg-indigo-50 transition-colors disabled:opacity-50"
                      title="Send renewal reminder"
                    >
                      <Mail className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              ))
            )}
          </>
        )}

        {activeTab === "dunning" && (
          <>
            {data.dunning.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <CreditCard className="h-8 w-8 mx-auto mb-2 text-gray-300" />
                <p>No accounts in dunning</p>
              </div>
            ) : (
              data.dunning.map((account) => (
                <div
                  key={account.userId}
                  className="flex items-center justify-between p-4 rounded-lg bg-red-50 border border-red-100"
                >
                  <div className="flex items-center gap-4">
                    <div className="p-2 rounded-lg bg-red-100">
                      <CreditCard className="h-5 w-5 text-red-600" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">
                        {account.name || "Unknown"}
                      </p>
                      <p className="text-xs text-gray-500">{account.email}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-bold text-red-600">
                      {account.failureCount} failed attempts
                    </p>
                    <p className="text-xs text-gray-500">
                      ${account.amount} outstanding
                    </p>
                    {account.lastAttempt && (
                      <p className="text-xs text-gray-400">
                        Last:{" "}
                        {new Date(account.lastAttempt).toLocaleDateString()}
                      </p>
                    )}
                  </div>
                </div>
              ))
            )}
          </>
        )}

        {activeTab === "churned" && (
          <>
            {data.churned30Days.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <UserMinus className="h-8 w-8 mx-auto mb-2 text-gray-300" />
                <p>No churned accounts in last 30 days</p>
              </div>
            ) : (
              data.churned30Days.map((account) => (
                <div
                  key={account.userId}
                  className="flex items-center justify-between p-4 rounded-lg bg-gray-50"
                >
                  <div className="flex items-center gap-4">
                    <div className="p-2 rounded-lg bg-gray-200">
                      <UserMinus className="h-5 w-5 text-gray-600" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">
                        {account.companyName || account.name || "Unknown"}
                      </p>
                      <p className="text-xs text-gray-500">{account.email}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-gray-600">
                      Lost ${account.lostMrr}/mo
                    </p>
                    <p className="text-xs text-gray-400">
                      {account.lifetimeDays} days as customer
                    </p>
                    <p className="text-xs text-gray-400">
                      Churned:{" "}
                      {new Date(account.churnedAt).toLocaleDateString()}
                    </p>
                  </div>
                </div>
              ))
            )}
          </>
        )}
      </div>

      {/* Footer */}
      <div className="mt-4 pt-4 border-t border-gray-100 text-xs text-gray-500 text-right">
        Last updated: {new Date().toLocaleTimeString()}
      </div>
    </div>
  );
}
