"use client";

import { useState, useEffect, useCallback } from "react";
import { CredentialRequirement } from "@/lib/types";
import { X, Check, Loader2, Shield, Key, ExternalLink, PartyPopper } from "lucide-react";

interface CredentialStatus {
  service: string;
  connectedAt: string;
}

interface ConnectModalProps {
  credential: CredentialRequirement;
  onClose: () => void;
  onConnect: (type: string, service: string) => Promise<void>;
}

function ConnectModal({ credential, onClose, onConnect }: ConnectModalProps) {
  const [step, setStep] = useState<"info" | "connecting" | "done">("info");
  const [apiKey, setApiKey] = useState("");

  const isApiKey = credential.type.endsWith("-api");
  const isWebhook = credential.type.endsWith("-webhook");

  const handleAuthorize = async () => {
    setStep("connecting");
    // Simulate OAuth delay
    await new Promise((r) => setTimeout(r, 1500));
    await onConnect(credential.type, credential.service);
    setStep("done");
    setTimeout(onClose, 800);
  };

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 9999,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(0, 0, 0, 0.7)",
        backdropFilter: "blur(4px)",
      }}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        style={{
          backgroundColor: "#2b2d31",
          borderRadius: 12,
          padding: 24,
          width: "100%",
          maxWidth: 420,
          border: "1px solid #3f4147",
          boxShadow: "0 20px 60px rgba(0,0,0,0.5)",
          animation: "fadeInScale 0.2s ease-out",
        }}
      >
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div
              style={{
                width: 48,
                height: 48,
                borderRadius: 12,
                backgroundColor: "rgba(255, 109, 90, 0.15)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 24,
              }}
            >
              {credential.icon}
            </div>
            <div>
              <h3 style={{ color: "#ffffff", fontSize: 16, fontWeight: 600, margin: 0 }}>
                Connect {credential.service}
              </h3>
              <p style={{ color: "#72767d", fontSize: 13, margin: "2px 0 0" }}>
                {credential.description}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            style={{
              background: "none",
              border: "none",
              color: "#72767d",
              cursor: "pointer",
              padding: 4,
              borderRadius: 4,
              display: "flex",
            }}
          >
            <X size={18} />
          </button>
        </div>

        {/* Body */}
        {step === "info" && (
          <>
            <div
              style={{
                backgroundColor: "#1a1d23",
                borderRadius: 8,
                padding: 16,
                marginBottom: 16,
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <Shield size={14} style={{ color: "#3fb950" }} />
                <span style={{ color: "#dcddde", fontSize: 13, fontWeight: 500 }}>
                  Secure Connection
                </span>
              </div>
              <p style={{ color: "#96989d", fontSize: 12, margin: 0, lineHeight: 1.5 }}>
                {isApiKey
                  ? `Enter your ${credential.service} API key to enable this integration. Your key is stored securely and only used for workflow execution.`
                  : isWebhook
                    ? `Enter your ${credential.service} webhook URL. This will be used to send data from your workflows.`
                    : `You'll be redirected to ${credential.service} to authorize access. We only request the minimum permissions needed.`}
              </p>
            </div>

            {(isApiKey || isWebhook) ? (
              <div style={{ marginBottom: 16 }}>
                <label style={{ color: "#dcddde", fontSize: 13, fontWeight: 500, display: "block", marginBottom: 6 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <Key size={13} />
                    {isApiKey ? "API Key" : "Webhook URL"}
                  </div>
                </label>
                <input
                  type={isApiKey ? "password" : "text"}
                  placeholder={isApiKey ? "sk-..." : "https://discord.com/api/webhooks/..."}
                  value={apiKey}
                  onChange={(e) => setApiKey(e.target.value)}
                  style={{
                    width: "100%",
                    padding: "10px 12px",
                    backgroundColor: "#1a1d23",
                    border: "1px solid #3f4147",
                    borderRadius: 6,
                    color: "#dcddde",
                    fontSize: 13,
                    outline: "none",
                    boxSizing: "border-box",
                    fontFamily: "monospace",
                  }}
                />
              </div>
            ) : (
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                  padding: "10px 12px",
                  backgroundColor: "rgba(255, 109, 90, 0.08)",
                  borderRadius: 6,
                  marginBottom: 16,
                }}
              >
                <ExternalLink size={14} style={{ color: "#ff6d5a" }} />
                <span style={{ color: "#dcddde", fontSize: 12 }}>
                  A new window will open for authorization
                </span>
              </div>
            )}

            <button
              onClick={handleAuthorize}
              disabled={(isApiKey || isWebhook) && !apiKey.trim()}
              style={{
                width: "100%",
                padding: "10px 16px",
                backgroundColor: ((isApiKey || isWebhook) && !apiKey.trim()) ? "#3f4147" : "#ff6d5a",
                color: ((isApiKey || isWebhook) && !apiKey.trim()) ? "#72767d" : "#ffffff",
                border: "none",
                borderRadius: 8,
                fontSize: 14,
                fontWeight: 600,
                cursor: ((isApiKey || isWebhook) && !apiKey.trim()) ? "not-allowed" : "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 8,
                transition: "all 0.15s ease",
              }}
            >
              {isApiKey ? (
                <>
                  <Key size={16} />
                  Save API Key
                </>
              ) : isWebhook ? (
                <>
                  <Key size={16} />
                  Save Webhook URL
                </>
              ) : (
                <>
                  <ExternalLink size={16} />
                  Authorize {credential.service}
                </>
              )}
            </button>
          </>
        )}

        {step === "connecting" && (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <Loader2
              size={32}
              style={{ color: "#ff6d5a", animation: "spin 1s linear infinite" }}
            />
            <p style={{ color: "#dcddde", fontSize: 14, marginTop: 12 }}>
              Connecting to {credential.service}...
            </p>
            <p style={{ color: "#72767d", fontSize: 12 }}>
              Verifying your credentials
            </p>
          </div>
        )}

        {step === "done" && (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <div
              style={{
                width: 48,
                height: 48,
                borderRadius: "50%",
                backgroundColor: "rgba(63, 185, 80, 0.2)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                margin: "0 auto 12px",
              }}
            >
              <Check size={24} style={{ color: "#3fb950" }} />
            </div>
            <p style={{ color: "#3fb950", fontSize: 14, fontWeight: 600 }}>
              {credential.service} Connected!
            </p>
          </div>
        )}
      </div>

      <style>{`
        @keyframes fadeInScale {
          from { opacity: 0; transform: scale(0.95); }
          to { opacity: 1; transform: scale(1); }
        }
        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}

interface CredentialConnectorProps {
  credentials: CredentialRequirement[];
}

export function CredentialConnector({ credentials }: CredentialConnectorProps) {
  const [connectedTypes, setConnectedTypes] = useState<Record<string, CredentialStatus>>({});
  const [connectingModal, setConnectingModal] = useState<CredentialRequirement | null>(null);
  const [showCelebration, setShowCelebration] = useState(false);
  const [isVisible, setIsVisible] = useState(false);

  // Animate in on mount
  useEffect(() => {
    const timer = setTimeout(() => setIsVisible(true), 50);
    return () => clearTimeout(timer);
  }, []);

  // Fetch existing credential status on mount
  useEffect(() => {
    fetch("/api/credentials")
      .then((r) => r.json())
      .then((data) => {
        if (data.credentials) {
          setConnectedTypes(data.credentials);
        }
      })
      .catch(() => {});
  }, []);

  const handleConnect = useCallback(async (type: string, service: string) => {
    await fetch("/api/credentials", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ type, service }),
    });
    setConnectedTypes((prev) => ({
      ...prev,
      [type]: { service, connectedAt: new Date().toISOString() },
    }));
  }, []);

  // Check if all connected after state update
  useEffect(() => {
    if (credentials.length > 0) {
      const allConnected = credentials.every((c) => connectedTypes[c.type]);
      if (allConnected && Object.keys(connectedTypes).length > 0) {
        setShowCelebration(true);
      }
    }
  }, [connectedTypes, credentials]);

  const connectedCount = credentials.filter((c) => connectedTypes[c.type]).length;
  const totalCount = credentials.length;

  if (credentials.length === 0) return null;

  return (
    <>
      <div
        style={{
          backgroundColor: "#1a1d23",
          borderBottom: "1px solid #2f3136",
          padding: "16px 20px",
          transition: "all 0.3s ease",
          opacity: isVisible ? 1 : 0,
          transform: isVisible ? "translateY(0)" : "translateY(-8px)",
        }}
      >
        {/* Card */}
        <div
          style={{
            backgroundColor: "#2b2d31",
            borderRadius: 12,
            overflow: "hidden",
            border: "1px solid #3f4147",
          }}
        >
          {/* Header */}
          <div
            style={{
              padding: "14px 16px",
              borderBottom: "1px solid #3f4147",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 16 }}>🔗</span>
                <h3 style={{ color: "#ffffff", fontSize: 14, fontWeight: 600, margin: 0 }}>
                  Connect Your Apps
                </h3>
              </div>
              <p style={{ color: "#72767d", fontSize: 12, margin: "4px 0 0 24px" }}>
                These services need authentication to run your workflow
              </p>
            </div>
            <div
              style={{
                padding: "3px 10px",
                borderRadius: 12,
                fontSize: 12,
                fontWeight: 600,
                backgroundColor:
                  connectedCount === totalCount
                    ? "rgba(63, 185, 80, 0.15)"
                    : "rgba(255, 109, 90, 0.15)",
                color:
                  connectedCount === totalCount ? "#3fb950" : "#ff6d5a",
              }}
            >
              {connectedCount}/{totalCount}
            </div>
          </div>

          {/* Credential rows */}
          <div style={{ padding: "4px 0" }}>
            {credentials.map((cred, index) => {
              const isConnected = !!connectedTypes[cred.type];
              return (
                <div
                  key={cred.type}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    padding: "10px 16px",
                    borderBottom: index < credentials.length - 1 ? "1px solid rgba(63, 65, 71, 0.5)" : "none",
                    transition: "background-color 0.15s ease",
                  }}
                >
                  {/* Left: icon + info */}
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div
                      style={{
                        width: 36,
                        height: 36,
                        borderRadius: 8,
                        backgroundColor: isConnected
                          ? "rgba(63, 185, 80, 0.12)"
                          : "rgba(255, 109, 90, 0.12)",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: 18,
                        transition: "background-color 0.3s ease",
                      }}
                    >
                      {cred.icon}
                    </div>
                    <div>
                      <div style={{ color: "#dcddde", fontSize: 13, fontWeight: 500 }}>
                        {cred.service}
                      </div>
                      <div style={{ color: "#72767d", fontSize: 11 }}>
                        {cred.description}
                      </div>
                    </div>
                  </div>

                  {/* Right: status + button */}
                  <div>
                    {isConnected ? (
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 6,
                          padding: "5px 12px",
                          borderRadius: 6,
                          backgroundColor: "rgba(63, 185, 80, 0.12)",
                          color: "#3fb950",
                          fontSize: 12,
                          fontWeight: 600,
                          animation: "fadeIn 0.3s ease",
                        }}
                      >
                        <Check size={14} />
                        Connected
                      </div>
                    ) : (
                      <button
                        onClick={() => setConnectingModal(cred)}
                        style={{
                          padding: "5px 14px",
                          borderRadius: 6,
                          backgroundColor: "#ff6d5a",
                          color: "#ffffff",
                          border: "none",
                          fontSize: 12,
                          fontWeight: 600,
                          cursor: "pointer",
                          transition: "all 0.15s ease",
                          display: "flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                        onMouseEnter={(e) => {
                          (e.currentTarget as HTMLButtonElement).style.backgroundColor = "#ff8570";
                          (e.currentTarget as HTMLButtonElement).style.transform = "translateY(-1px)";
                        }}
                        onMouseLeave={(e) => {
                          (e.currentTarget as HTMLButtonElement).style.backgroundColor = "#ff6d5a";
                          (e.currentTarget as HTMLButtonElement).style.transform = "translateY(0)";
                        }}
                      >
                        Connect
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Footer */}
          {showCelebration ? (
            <div
              style={{
                padding: "12px 16px",
                borderTop: "1px solid #3f4147",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 8,
                backgroundColor: "rgba(63, 185, 80, 0.06)",
                animation: "fadeIn 0.4s ease",
              }}
            >
              <PartyPopper size={16} style={{ color: "#3fb950" }} />
              <span style={{ color: "#3fb950", fontSize: 13, fontWeight: 500 }}>
                All apps connected! Your workflow is ready to run.
              </span>
            </div>
          ) : (
            <div
              style={{
                padding: "10px 16px",
                borderTop: "1px solid #3f4147",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <span style={{ color: "#72767d", fontSize: 11 }}>
                Connect each service to enable your workflow
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Modal portal */}
      {connectingModal && (
        <ConnectModal
          credential={connectingModal}
          onClose={() => setConnectingModal(null)}
          onConnect={handleConnect}
        />
      )}

      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
      `}</style>
    </>
  );
}
