"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { api } from "@/lib/api";
import {
  CreditCard,
  Building2,
  Calendar,
  AlertTriangle,
  CheckCircle,
  XCircle,
  RefreshCw,
  Pause,
  Play,
  Clock,
  Cpu,
  Users,
  Search,
} from "lucide-react";

interface Subscription {
  tenant_id: string;
  tenant_name: string;
  subscription_plan: string;
  max_devices: number;
  max_sensors: number;
  max_users: number;
  current_devices: number;
  current_sensors: number;
  current_users: number;
  subscription_start?: string;
  subscription_end?: string;
  is_subscription_active: boolean;
  auto_renew: boolean;
  days_remaining?: number;
  is_expired: boolean;
}

interface SubscriptionStats {
  total_tenants: number;
  active_subscriptions: number;
  inactive_subscriptions: number;
  expiring_in_30_days: number;
  by_plan: Record<string, number>;
}

export default function SubscriptionsPage() {
  const API_URL = process.env.NEXT_PUBLIC_API_URL || "https://smart-life.online";
  const t = useTranslations("subscriptions");
  const [stats, setStats] = useState<SubscriptionStats | null>(null);
  const [expiring, setExpiring] = useState<any[]>([]);
  const [expired, setExpired] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch subscription stats
        const statsRes = await fetch(`${API_URL}/api/v1/subscriptions/stats`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        if (statsRes.ok) {
          setStats(await statsRes.json());
        }

        // Fetch expiring subscriptions
        const expiringRes = await fetch(`${API_URL}/api/v1/subscriptions/expiring?days=30`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        if (expiringRes.ok) {
          setExpiring(await expiringRes.json());
        }

        // Fetch expired subscriptions
        const expiredRes = await fetch(`${API_URL}/api/v1/subscriptions/expired`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        if (expiredRes.ok) {
          setExpired(await expiredRes.json());
        }
      } catch (error) {
        console.error("Failed to fetch subscription data:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const handleActivate = async (tenantId: string) => {
    try {
      await fetch(`${API_URL}/api/v1/subscriptions/tenant/${tenantId}/activate`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      window.location.reload();
    } catch (error) {
      console.error("Failed to activate subscription:", error);
    }
  };

  const handleDeactivate = async (tenantId: string) => {
    try {
      await fetch(`${API_URL}/api/v1/subscriptions/tenant/${tenantId}/deactivate`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      window.location.reload();
    } catch (error) {
      console.error("Failed to deactivate subscription:", error);
    }
  };

  const handleRenew = async (tenantId: string, months: number = 1) => {
    try {
      await fetch(`${API_URL}/api/v1/subscriptions/tenant/${tenantId}/renew`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ months }),
      });
      window.location.reload();
    } catch (error) {
      console.error("Failed to renew subscription:", error);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
          {t("title")}
        </h1>
        <p className="text-gray-500 dark:text-gray-400">{t("subtitle")}</p>
      </div>

      {/* Stats Cards */}
      {stats && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
                <Building2 className="w-6 h-6 text-blue-600 dark:text-blue-400" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {stats.total_tenants}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("totalTenants")}</p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-xl bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                <CheckCircle className="w-6 h-6 text-green-600 dark:text-green-400" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {stats.active_subscriptions}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("activeSubscriptions")}</p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-xl bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <XCircle className="w-6 h-6 text-red-600 dark:text-red-400" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {stats.inactive_subscriptions}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("inactiveSubscriptions")}</p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-xl bg-yellow-100 dark:bg-yellow-900/30 flex items-center justify-center">
                <AlertTriangle className="w-6 h-6 text-yellow-600 dark:text-yellow-400" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {stats.expiring_in_30_days}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("expiringSoon")}</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Plans Distribution */}
      {stats && stats.by_plan && Object.keys(stats.by_plan).length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            {t("planDistribution")}
          </h2>
          <div className="flex flex-wrap gap-4">
            {Object.entries(stats.by_plan).map(([plan, count]) => (
              <div
                key={plan}
                className="flex items-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 rounded-lg"
              >
                <CreditCard className="w-4 h-4 text-primary" />
                <span className="font-medium capitalize">{plan}</span>
                <span className="text-gray-500 dark:text-gray-400">({count})</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Expiring Soon */}
      {expiring.length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
            <Clock className="w-5 h-5 text-yellow-500" />
            {t("expiringSoonTitle")}
          </h2>
          <div className="space-y-3">
            {expiring.map((item) => (
              <div
                key={item.tenant_id}
                className="flex items-center justify-between p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800"
              >
                <div className="flex items-center gap-3">
                  <Building2 className="w-5 h-5 text-yellow-600" />
                  <div>
                    <p className="font-medium text-gray-900 dark:text-white">
                      {item.tenant_name}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {t("expiresIn")} {item.days_remaining} {t("days")} • {item.subscription_plan}
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => handleRenew(item.tenant_id)}
                  className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
                >
                  <RefreshCw className="w-4 h-4" />
                  {t("renew")}
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Expired */}
      {expired.length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
            <XCircle className="w-5 h-5 text-red-500" />
            {t("expiredTitle")}
          </h2>
          <div className="space-y-3">
            {expired.map((item) => (
              <div
                key={item.tenant_id}
                className="flex items-center justify-between p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800"
              >
                <div className="flex items-center gap-3">
                  <Building2 className="w-5 h-5 text-red-600" />
                  <div>
                    <p className="font-medium text-gray-900 dark:text-white">
                      {item.tenant_name}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {t("expiredSince")} {item.days_expired} {t("days")} • {item.subscription_plan}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleRenew(item.tenant_id)}
                    className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
                  >
                    <RefreshCw className="w-4 h-4" />
                    {t("renew")}
                  </button>
                  <button
                    onClick={() => handleDeactivate(item.tenant_id)}
                    className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
                  >
                    <Pause className="w-4 h-4" />
                    {t("deactivate")}
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* No Data */}
      {!stats && expiring.length === 0 && expired.length === 0 && (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <CreditCard className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            {t("noData")}
          </h3>
          <p className="text-gray-500 dark:text-gray-400">{t("noDataDesc")}</p>
        </div>
      )}
    </div>
  );
}
