"use client";

/**
 * Social Dashboard Client Component
 * Manages social media account connections and displays queue status
 */

import { useState, useEffect, useCallback } from "react";
import SocialAccountCard from "./SocialAccountCard";
import ConnectPlatformModal from "./ConnectPlatformModal";
import type {
  SocialPlatform,
  SocialAccountOutput,
  SocialIntegrationStatus,
} from "@/lib/types/social-media.types";

interface AccountWithMeta extends SocialAccountOutput {
  platformConfig?: {
    name: string;
    icon: string;
    maxChars: number;
    maxHashtags: number;
    mediaRequired: boolean;
  };
}

export default function SocialDashboardClient() {
  const [accounts, setAccounts] = useState<AccountWithMeta[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // Check for OAuth callback success/error in URL
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const success = params.get("success");
    const errorMsg = params.get("error");
    const platform = params.get("platform");
    const accountCount = params.get("accounts");

    if (success === "true" && platform) {
      setSuccessMessage(
        `Successfully connected ${accountCount || ""} ${platform} account(s)!`,
      );
      // Clear URL params
      window.history.replaceState({}, "", window.location.pathname);
    } else if (errorMsg) {
      setError(decodeURIComponent(errorMsg));
      window.history.replaceState({}, "", window.location.pathname);
    }
  }, []);

  const fetchAccounts = useCallback(async () => {
    try {
      const response = await fetch("/api/staff/dashboard/social/accounts");
      const data = await response.json();

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

      setAccounts(data.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load accounts");
    } finally {
      setIsLoading(false);
    }
  }, []);

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

  const handleConnect = async (platform: SocialPlatform) => {
    try {
      const response = await fetch("/api/staff/dashboard/social/accounts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ platform }),
      });

      const data = await response.json();

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

      // Redirect to OAuth URL
      window.location.href = data.data.url;
    } catch (err) {
      setError(err instanceof Error ? err.message : "Connection failed");
    }
  };

  const handleDisconnect = async (accountId: string) => {
    try {
      const response = await fetch(
        `/api/staff/dashboard/social/accounts/${accountId}`,
        { method: "DELETE" },
      );

      const data = await response.json();

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

      setAccounts((prev) => prev.filter((a) => a.id !== accountId));
      setSuccessMessage("Account disconnected successfully");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Disconnect failed");
    }
  };

  const handleRefreshToken = async (accountId: string) => {
    try {
      // For now, reconnecting is the best option
      const account = accounts.find((a) => a.id === accountId);
      if (account) {
        await handleConnect(account.platform);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Token refresh failed");
    }
  };

  // Clear messages after timeout
  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [successMessage]);

  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => setError(null), 10000);
      return () => clearTimeout(timer);
    }
  }, [error]);

  // Get connected platforms
  const connectedPlatforms = new Set(accounts.map((a) => a.platform));

  // connectedPlatforms is used for the modal prop

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

  return (
    <div className="space-y-6">
      {/* Success Message */}
      {successMessage && (
        <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
          <p className="text-green-800 dark:text-green-200">{successMessage}</p>
        </div>
      )}

      {/* Error Message */}
      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-800 dark:text-red-200">{error}</p>
        </div>
      )}

      {/* Stats Overview */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <StatCard
          label="Connected Accounts"
          value={accounts.length}
          icon={
            <svg
              className="w-6 h-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
              />
            </svg>
          }
        />
        <StatCard
          label="Facebook"
          value={accounts.filter((a) => a.platform === "FACEBOOK").length}
          icon={<span className="text-xl font-bold">f</span>}
          color="blue"
        />
        <StatCard
          label="Instagram"
          value={accounts.filter((a) => a.platform === "INSTAGRAM").length}
          icon={<span className="text-xl font-bold">IG</span>}
          color="pink"
        />
        <StatCard
          label="Active"
          value={accounts.filter((a) => a.status === "CONNECTED").length}
          icon={
            <svg
              className="w-6 h-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          }
          color="green"
        />
      </div>

      {/* Actions Bar */}
      <div className="flex justify-between items-center">
        <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
          Connected Accounts
        </h2>
        <button
          onClick={() => setIsModalOpen(true)}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
        >
          <svg
            className="w-5 h-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 6v6m0 0v6m0-6h6m-6 0H6"
            />
          </svg>
          Connect Account
        </button>
      </div>

      {/* Accounts Grid */}
      {accounts.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg">
          <svg
            className="mx-auto h-12 w-12 text-gray-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
            />
          </svg>
          <h3 className="mt-2 text-sm font-medium text-gray-900 dark:text-white">
            No accounts connected
          </h3>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            Connect your social media accounts to start publishing content.
          </p>
          <button
            onClick={() => setIsModalOpen(true)}
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Connect Your First Account
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {accounts.map((account) => (
            <SocialAccountCard
              key={account.id}
              id={account.id}
              platform={account.platform}
              accountName={account.accountName}
              status={account.status as SocialIntegrationStatus}
              tokenExpiry={account.tokenExpiry}
              onDisconnect={handleDisconnect}
              onRefreshToken={handleRefreshToken}
            />
          ))}
          {/* Coming soon cards */}
          {!connectedPlatforms.has("TWITTER") && (
            <SocialAccountCard
              id="twitter-coming-soon"
              platform="TWITTER"
              accountName=""
              status="DISCONNECTED"
              tokenExpiry={null}
              onDisconnect={() => {}}
              onRefreshToken={() => {}}
              isComingSoon
            />
          )}
          {!connectedPlatforms.has("TIKTOK") && (
            <SocialAccountCard
              id="tiktok-coming-soon"
              platform="TIKTOK"
              accountName=""
              status="DISCONNECTED"
              tokenExpiry={null}
              onDisconnect={() => {}}
              onRefreshToken={() => {}}
              isComingSoon
            />
          )}
        </div>
      )}

      {/* Connect Platform Modal */}
      <ConnectPlatformModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onConnect={handleConnect}
        connectedPlatforms={Array.from(connectedPlatforms)}
      />
    </div>
  );
}

interface StatCardProps {
  label: string;
  value: number;
  icon: React.ReactNode;
  color?: "default" | "blue" | "pink" | "green";
}

function StatCard({ label, value, icon, color = "default" }: StatCardProps) {
  const colorClasses = {
    default: "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",
    blue: "bg-blue-100 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400",
    pink: "bg-pink-100 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400",
    green:
      "bg-green-100 text-green-600 dark:bg-green-900/20 dark:text-green-400",
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
            {label}
          </p>
          <p className="text-2xl font-bold text-gray-900 dark:text-white">
            {value}
          </p>
        </div>
        <div className={`p-3 rounded-full ${colorClasses[color]}`}>{icon}</div>
      </div>
    </div>
  );
}
