"use client";

import { useState } from "react";
import {
  AlertCircle,
  CheckCircle,
  Clock,
  ExternalLink,
  MoreVertical,
  RefreshCw,
  Trash2,
  XCircle,
} from "lucide-react";
import type {
  SocialPlatform,
  SocialIntegrationStatus,
} from "@/lib/types/social-media.types";

// Platform icons as SVG components
const PlatformIcons: Record<
  SocialPlatform,
  React.FC<{ className?: string }>
> = {
  FACEBOOK: ({ className }) => (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
    </svg>
  ),
  INSTAGRAM: ({ className }) => (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z" />
    </svg>
  ),
  TWITTER: ({ className }) => (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
    </svg>
  ),
  TIKTOK: ({ className }) => (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z" />
    </svg>
  ),
};

// Platform colors
const PLATFORM_COLORS: Record<
  SocialPlatform,
  { bg: string; text: string; border: string }
> = {
  FACEBOOK: {
    bg: "bg-blue-50",
    text: "text-blue-600",
    border: "border-blue-200",
  },
  INSTAGRAM: {
    bg: "bg-pink-50",
    text: "text-pink-600",
    border: "border-pink-200",
  },
  TWITTER: {
    bg: "bg-gray-50",
    text: "text-gray-900",
    border: "border-gray-200",
  },
  TIKTOK: {
    bg: "bg-gray-50",
    text: "text-gray-900",
    border: "border-gray-200",
  },
};

// Platform display names
const PLATFORM_NAMES: Record<SocialPlatform, string> = {
  FACEBOOK: "Facebook",
  INSTAGRAM: "Instagram",
  TWITTER: "X (Twitter)",
  TIKTOK: "TikTok",
};

interface SocialAccountCardProps {
  id: string;
  platform: SocialPlatform;
  accountName: string;
  status: SocialIntegrationStatus;
  tokenExpiry: Date | null;
  onDisconnect: (id: string) => void;
  onRefreshToken: (id: string) => void;
  isComingSoon?: boolean;
}

export default function SocialAccountCard({
  id,
  platform,
  accountName,
  status,
  tokenExpiry,
  onDisconnect,
  onRefreshToken,
  isComingSoon = false,
}: SocialAccountCardProps) {
  const [showMenu, setShowMenu] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const Icon = PlatformIcons[platform];
  const colors = PLATFORM_COLORS[platform];
  const platformName = PLATFORM_NAMES[platform];

  // Calculate days until token expiry
  const daysUntilExpiry = tokenExpiry
    ? Math.ceil(
        (new Date(tokenExpiry).getTime() - Date.now()) / (1000 * 60 * 60 * 24),
      )
    : null;

  const isExpiringsSoon =
    daysUntilExpiry !== null && daysUntilExpiry <= 7 && daysUntilExpiry > 0;
  const isExpired =
    status === "TOKEN_EXPIRED" ||
    (daysUntilExpiry !== null && daysUntilExpiry <= 0);

  // Status badge configuration
  const statusConfig: Record<
    SocialIntegrationStatus,
    { icon: React.ElementType; label: string; className: string }
  > = {
    CONNECTED: {
      icon: CheckCircle,
      label: "Connected",
      className: "bg-green-100 text-green-700",
    },
    DISCONNECTED: {
      icon: XCircle,
      label: "Disconnected",
      className: "bg-gray-100 text-gray-700",
    },
    TOKEN_EXPIRED: {
      icon: AlertCircle,
      label: "Token Expired",
      className: "bg-red-100 text-red-700",
    },
    ERROR: {
      icon: AlertCircle,
      label: "Error",
      className: "bg-red-100 text-red-700",
    },
  };

  const currentStatus = statusConfig[status];
  const StatusIcon = currentStatus.icon;

  const handleDisconnect = () => {
    setIsLoading(true);
    setShowMenu(false);
    try {
      onDisconnect(id);
    } finally {
      setIsLoading(false);
    }
  };

  const handleRefreshToken = () => {
    setIsLoading(true);
    setShowMenu(false);
    try {
      onRefreshToken(id);
    } finally {
      setIsLoading(false);
    }
  };

  // Coming soon card variant
  if (isComingSoon) {
    return (
      <div
        className={`relative border ${colors.border} rounded-xl p-5 ${colors.bg} opacity-60`}
      >
        <div className="absolute top-3 right-3">
          <span className="px-2 py-1 text-xs font-medium bg-gray-200 text-gray-600 rounded-full">
            Coming Soon
          </span>
        </div>
        <div className="flex items-center gap-4">
          <div
            className={`p-3 rounded-xl ${colors.bg} border ${colors.border}`}
          >
            <Icon className={`h-8 w-8 ${colors.text}`} />
          </div>
          <div>
            <h3 className="font-semibold text-gray-900">{platformName}</h3>
            <p className="text-sm text-gray-500">Available in Phase 2</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`relative border rounded-xl p-5 transition-shadow hover:shadow-md ${
        isExpired
          ? "border-red-300 bg-red-50"
          : isExpiringsSoon
            ? "border-yellow-300 bg-yellow-50"
            : `${colors.border} bg-white`
      }`}
    >
      {/* Loading overlay */}
      {isLoading && (
        <div className="absolute inset-0 bg-white/80 rounded-xl flex items-center justify-center z-10">
          <RefreshCw className="h-6 w-6 text-gray-400 animate-spin" />
        </div>
      )}

      {/* Header */}
      <div className="flex items-start justify-between mb-4">
        <div className="flex items-center gap-3">
          <div
            className={`p-2.5 rounded-xl ${colors.bg} border ${colors.border}`}
          >
            <Icon className={`h-6 w-6 ${colors.text}`} />
          </div>
          <div>
            <h3 className="font-semibold text-gray-900">{platformName}</h3>
            <p className="text-sm text-gray-500">{accountName}</p>
          </div>
        </div>

        {/* Menu */}
        <div className="relative">
          <button
            onClick={() => setShowMenu(!showMenu)}
            className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition"
          >
            <MoreVertical className="h-5 w-5" />
          </button>

          {showMenu && (
            <>
              <div
                className="fixed inset-0 z-10"
                onClick={() => setShowMenu(false)}
              />
              <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-20">
                {(isExpired || isExpiringsSoon) && (
                  <button
                    onClick={handleRefreshToken}
                    className="flex items-center gap-2 w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-50"
                  >
                    <RefreshCw className="h-4 w-4" />
                    Refresh Token
                  </button>
                )}
                <button
                  onClick={handleDisconnect}
                  className="flex items-center gap-2 w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50"
                >
                  <Trash2 className="h-4 w-4" />
                  Disconnect
                </button>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Status */}
      <div className="flex items-center gap-2 mb-3">
        <span
          className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full ${currentStatus.className}`}
        >
          <StatusIcon className="h-3.5 w-3.5" />
          {currentStatus.label}
        </span>
      </div>

      {/* Token expiry warning */}
      {tokenExpiry && status === "CONNECTED" && (
        <div
          className={`flex items-center gap-2 text-sm ${
            isExpired
              ? "text-red-600"
              : isExpiringsSoon
                ? "text-yellow-600"
                : "text-gray-500"
          }`}
        >
          <Clock className="h-4 w-4" />
          {isExpired ? (
            <span>Token expired</span>
          ) : isExpiringsSoon ? (
            <span>Expires in {daysUntilExpiry} days</span>
          ) : (
            <span>Expires {new Date(tokenExpiry).toLocaleDateString()}</span>
          )}
        </div>
      )}

      {/* Action for expired/expiring tokens */}
      {(isExpired || isExpiringsSoon) && (
        <button
          onClick={handleRefreshToken}
          className="mt-4 w-full flex items-center justify-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition"
        >
          <RefreshCw className="h-4 w-4" />
          {isExpired ? "Reconnect Account" : "Refresh Token"}
        </button>
      )}

      {/* View on platform link */}
      {status === "CONNECTED" && !isExpired && (
        <a
          href={`https://${platform.toLowerCase()}.com`}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-4 flex items-center justify-center gap-2 text-sm text-gray-500 hover:text-gray-700"
        >
          <ExternalLink className="h-4 w-4" />
          View on {platformName}
        </a>
      )}
    </div>
  );
}
