"use client";

import { useState } from "react";
import {
  X,
  ExternalLink,
  Shield,
  CheckCircle,
  AlertCircle,
} from "lucide-react";
import type { SocialPlatform } 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 configuration for modal
const PLATFORM_CONFIG: Record<
  SocialPlatform,
  {
    name: string;
    description: string;
    permissions: string[];
    available: boolean;
    bgGradient: string;
    iconBg: string;
    iconColor: string;
  }
> = {
  FACEBOOK: {
    name: "Facebook",
    description:
      "Connect your Facebook Page to publish posts and track engagement.",
    permissions: [
      "Publish posts to your Page",
      "Read Page insights and metrics",
      "Manage Page comments",
    ],
    available: true,
    bgGradient: "from-blue-500 to-blue-600",
    iconBg: "bg-blue-100",
    iconColor: "text-blue-600",
  },
  INSTAGRAM: {
    name: "Instagram",
    description: "Connect your Instagram Business account via Facebook.",
    permissions: [
      "Publish photos and videos",
      "Read account insights",
      "View and reply to comments",
    ],
    available: false, // Coming soon
    bgGradient: "from-pink-500 via-purple-500 to-orange-500",
    iconBg: "bg-gradient-to-br from-pink-100 to-purple-100",
    iconColor: "text-pink-600",
  },
  TWITTER: {
    name: "X (Twitter)",
    description: "Connect your X account to publish tweets and threads.",
    permissions: [
      "Post tweets on your behalf",
      "Read your profile",
      "Access offline",
    ],
    available: false, // Coming soon
    bgGradient: "from-gray-800 to-gray-900",
    iconBg: "bg-gray-100",
    iconColor: "text-gray-900",
  },
  TIKTOK: {
    name: "TikTok",
    description: "Connect your TikTok Business account to publish videos.",
    permissions: ["Upload videos to your account", "Read basic profile info"],
    available: false, // Coming soon
    bgGradient: "from-gray-900 via-pink-600 to-cyan-400",
    iconBg: "bg-gray-100",
    iconColor: "text-gray-900",
  },
};

interface ConnectPlatformModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConnect: (platform: SocialPlatform) => void;
  isConnecting?: boolean;
  connectedPlatforms?: SocialPlatform[];
}

export default function ConnectPlatformModal({
  isOpen,
  onClose,
  onConnect,
  isConnecting = false,
  connectedPlatforms = [],
}: ConnectPlatformModalProps) {
  const [selectedPlatform, setSelectedPlatform] =
    useState<SocialPlatform | null>(null);
  const [step, setStep] = useState<"select" | "confirm">("select");

  const handleSelectPlatform = (platform: SocialPlatform) => {
    if (!PLATFORM_CONFIG[platform].available) return;
    if (connectedPlatforms.includes(platform)) return;
    setSelectedPlatform(platform);
    setStep("confirm");
  };

  const handleConnect = () => {
    if (selectedPlatform) {
      onConnect(selectedPlatform);
    }
  };

  const handleBack = () => {
    setStep("select");
    setSelectedPlatform(null);
  };

  const handleClose = () => {
    setStep("select");
    setSelectedPlatform(null);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 transition-opacity"
        onClick={handleClose}
      />

      {/* Modal */}
      <div className="flex min-h-full items-center justify-center p-4">
        <div className="relative bg-white rounded-2xl shadow-xl max-w-lg w-full overflow-hidden">
          {/* Close button */}
          <button
            onClick={handleClose}
            className="absolute top-4 right-4 p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition z-10"
          >
            <X className="h-5 w-5" />
          </button>

          {step === "select" ? (
            <>
              {/* Header */}
              <div className="px-6 pt-6 pb-4">
                <h2 className="text-xl font-bold text-gray-900">
                  Connect Social Account
                </h2>
                <p className="mt-1 text-sm text-gray-500">
                  Choose a platform to connect to your dashboard
                </p>
              </div>

              {/* Platform list */}
              <div className="px-6 pb-6 space-y-3">
                {(Object.keys(PLATFORM_CONFIG) as SocialPlatform[]).map(
                  (platform) => {
                    const config = PLATFORM_CONFIG[platform];
                    const Icon = PlatformIcons[platform];
                    const isConnected = connectedPlatforms.includes(platform);
                    const isAvailable = config.available;

                    return (
                      <button
                        key={platform}
                        onClick={() => handleSelectPlatform(platform)}
                        disabled={!isAvailable || isConnected}
                        className={`w-full flex items-center gap-4 p-4 rounded-xl border-2 transition ${
                          isConnected
                            ? "border-green-200 bg-green-50 cursor-default"
                            : isAvailable
                              ? "border-gray-200 hover:border-gray-300 hover:bg-gray-50 cursor-pointer"
                              : "border-gray-100 bg-gray-50 cursor-not-allowed opacity-60"
                        }`}
                      >
                        <div className={`p-3 rounded-xl ${config.iconBg}`}>
                          <Icon className={`h-6 w-6 ${config.iconColor}`} />
                        </div>
                        <div className="flex-1 text-left">
                          <div className="flex items-center gap-2">
                            <span className="font-semibold text-gray-900">
                              {config.name}
                            </span>
                            {!isAvailable && (
                              <span className="px-2 py-0.5 text-xs font-medium bg-gray-200 text-gray-600 rounded-full">
                                Coming Soon
                              </span>
                            )}
                            {isConnected && (
                              <span className="px-2 py-0.5 text-xs font-medium bg-green-100 text-green-700 rounded-full">
                                Connected
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-gray-500 mt-0.5">
                            {config.description}
                          </p>
                        </div>
                        {isAvailable && !isConnected && (
                          <ExternalLink className="h-5 w-5 text-gray-400" />
                        )}
                        {isConnected && (
                          <CheckCircle className="h-5 w-5 text-green-500" />
                        )}
                      </button>
                    );
                  },
                )}
              </div>
            </>
          ) : (
            <>
              {/* Confirm step */}
              {selectedPlatform && (
                <>
                  {/* Gradient header */}
                  <div
                    className={`h-24 bg-gradient-to-r ${PLATFORM_CONFIG[selectedPlatform].bgGradient}`}
                  />

                  {/* Content */}
                  <div className="px-6 pb-6 -mt-12">
                    {/* Platform icon */}
                    <div className="flex justify-center mb-4">
                      <div className="p-4 bg-white rounded-2xl shadow-lg">
                        {(() => {
                          const Icon = PlatformIcons[selectedPlatform];
                          return (
                            <Icon
                              className={`h-10 w-10 ${PLATFORM_CONFIG[selectedPlatform].iconColor}`}
                            />
                          );
                        })()}
                      </div>
                    </div>

                    {/* Title */}
                    <h2 className="text-xl font-bold text-gray-900 text-center">
                      Connect {PLATFORM_CONFIG[selectedPlatform].name}
                    </h2>
                    <p className="mt-2 text-sm text-gray-500 text-center">
                      {PLATFORM_CONFIG[selectedPlatform].description}
                    </p>

                    {/* Permissions */}
                    <div className="mt-6 p-4 bg-gray-50 rounded-xl">
                      <div className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-3">
                        <Shield className="h-4 w-4" />
                        Required Permissions
                      </div>
                      <ul className="space-y-2">
                        {PLATFORM_CONFIG[selectedPlatform].permissions.map(
                          (permission, index) => (
                            <li
                              key={index}
                              className="flex items-center gap-2 text-sm text-gray-600"
                            >
                              <CheckCircle className="h-4 w-4 text-green-500 flex-shrink-0" />
                              {permission}
                            </li>
                          ),
                        )}
                      </ul>
                    </div>

                    {/* Security note */}
                    <div className="mt-4 flex items-start gap-2 text-xs text-gray-500">
                      <AlertCircle className="h-4 w-4 flex-shrink-0 mt-0.5" />
                      <span>
                        Your access token is encrypted and stored securely. You
                        can disconnect at any time.
                      </span>
                    </div>

                    {/* Actions */}
                    <div className="mt-6 flex gap-3">
                      <button
                        onClick={handleBack}
                        className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-xl transition"
                      >
                        Back
                      </button>
                      <button
                        onClick={handleConnect}
                        disabled={isConnecting}
                        className={`flex-1 px-4 py-2.5 text-sm font-medium text-white rounded-xl transition ${
                          isConnecting
                            ? "bg-gray-400 cursor-not-allowed"
                            : `bg-gradient-to-r ${PLATFORM_CONFIG[selectedPlatform].bgGradient} hover:opacity-90`
                        }`}
                      >
                        {isConnecting ? "Connecting..." : "Connect Account"}
                      </button>
                    </div>
                  </div>
                </>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
