import { useState, useEffect } from "react";
import { Modal } from "@/Components/UI/Modal";
import { Button } from "@/Components/UI/Button";
import PlatformIcon from "@/Components/UI/PlatformIcon";
import { Input } from "@/Components/UI/Input";
import { Label } from "@/Components/UI/Label";
import { Users, ChevronRight, Sparkles, CheckCircle, Clock, AlertTriangle, Settings } from "lucide-react";
import { route } from "ziggy-js";
import { router } from "@inertiajs/react";

export default function ConnectAccountModal({ isOpen, onClose, platforms = [], selectedPlatform: preSelectedPlatform = null, t }) {
  const [selectedPlatform, setSelectedPlatform] = useState(preSelectedPlatform);
  const [accountName, setAccountName] = useState("");
  const [isConnecting, setIsConnecting] = useState(false);
  const [accountCreated, setAccountCreated] = useState(false);
  const [createdAccount, setCreatedAccount] = useState(null);
  const [configError, setConfigError] = useState(null);

  // Update selected platform when prop changes
  useEffect(() => {
    if (preSelectedPlatform) {
      setSelectedPlatform(preSelectedPlatform);
      setAccountName("");
      setAccountCreated(false);
      setCreatedAccount(null);
      setConfigError(null);
    } else if (isOpen) {
      // Reset to platform selection when opening modal without pre-selected platform
      setSelectedPlatform(null);
    }
  }, [preSelectedPlatform, isOpen]);

  const handlePlatformSelect = (platform) => {
    setSelectedPlatform(platform);
    setAccountName("");
  };

  const handleCreateAccount = () => {
    if (!selectedPlatform || !accountName.trim()) return;

    setIsConnecting(true);

    // Create account label in database first
    router.post(route("user.platform.account.create"), {
      label: accountName,
      platform_id: selectedPlatform.id,
      platform_slug: selectedPlatform.slug
    }, {
      preserveScroll: true,
      onSuccess: (response) => {
        setIsConnecting(false);
        setAccountCreated(true);
        setCreatedAccount(response?.props?.account || {
          label: accountName,
          platform: selectedPlatform
        });
      },
      onError: () => {
        setIsConnecting(false);
      }
    });
  };

  const handleConnectNow = () => {
    // Check if platform is configured before connecting
    if (!isValidPlatformConfig(selectedPlatform)) {
      setConfigError({
        platform: selectedPlatform,
        message: `${selectedPlatform.name} API is not configured. Please configure the platform settings first.`
      });
      return;
    }

    // Redirect to OAuth connection
    const connectUrl = route("user.account.connect", {
      medium: selectedPlatform.slug,
      account_id: createdAccount?.id
    });
    window.location.href = connectUrl;
  };

  const isValidPlatformConfig = (platform) => {
    // Check if platform has required configuration
    // TikTok uses client_key instead of client_id
    const hasClientId = platform?.configuration?.client_id || platform?.configuration?.client_key;
    const hasClientSecret = platform?.configuration?.client_secret;
    return platform?.configuration && hasClientId && hasClientSecret;
  };

  const handleConfigurePlatform = () => {
    const settingsUrl = route("user.platform.setting", selectedPlatform.id);
    window.location.href = settingsUrl;
  };

  const handleConnectLater = () => {
    onClose();
  };

  const handleBack = () => {
    // If there's a pre-selected platform, close modal instead of going back to platform selection
    if (preSelectedPlatform) {
      handleModalClose();
    } else {
      setSelectedPlatform(null);
      setAccountName("");
    }
  };

  const handleModalClose = () => {
    // Reset to pre-selected platform if provided, otherwise null
    setSelectedPlatform(preSelectedPlatform);
    setAccountName("");
    setIsConnecting(false);
    setAccountCreated(false);
    setCreatedAccount(null);
    setConfigError(null);
    onClose();
  };

  const getModalTitle = () => {
    if (configError) return `${configError.platform?.name} Configuration Required`;
    if (accountCreated) return `${selectedPlatform?.name} Account Created`;
    if (selectedPlatform) return `Connect ${selectedPlatform.name} Account`;
    return "Connect Social Account";
  };

  const renderContent = () => {
    // Configuration Error View
    if (configError) {
      return (
        <div className="space-y-6 text-center">
          <div className="flex flex-col items-center gap-4">
            <div className="p-4 bg-red-100 dark:bg-red-900/20 rounded-full">
              <AlertTriangle className="w-12 h-12 text-red-600 dark:text-red-400" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
                {t("Platform Not Configured")}
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                {configError.message}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-zinc-800 rounded-lg">
            <div className="p-2 bg-white dark:bg-zinc-900 rounded-lg shadow-sm">
              <PlatformIcon slug={configError.platform?.slug} size={24} />
            </div>
            <div className="text-left">
              <p className="font-medium text-gray-900 dark:text-gray-100">
                {configError.platform?.name}
              </p>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t("Requires API Configuration")}
              </p>
            </div>
          </div>

          <div className="p-4 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800">
            <div className="flex items-start gap-3">
              <Settings className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5" />
              <div className="text-left flex-1">
                <h4 className="text-sm font-medium text-amber-900 dark:text-amber-300 mb-1">
                  {t("Configuration Required")}
                </h4>
                <p className="text-xs text-amber-700 dark:text-amber-400">
                  {t("To connect")} {configError.platform?.name} {t("accounts, you need to configure API credentials (Client ID, Client Secret, etc.) in the platform settings.")}
                </p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              onClick={handleModalClose}
              className="flex-1"
            >
              {t("Cancel")}
            </Button>
            <Button
              onClick={handleConfigurePlatform}
              className="flex-1 bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
            >
              <Settings className="w-4 h-4 mr-2" />
              {t("Configure Platform")}
            </Button>
          </div>
        </div>
      );
    }

    // Account Created Success View
    if (accountCreated) {
      return (
        <div className="space-y-6 text-center">
          <div className="flex flex-col items-center gap-4">
            <div className="p-4 bg-emerald-100 dark:bg-emerald-900/20 rounded-full">
              <CheckCircle className="w-12 h-12 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
                {t("Account Label Created Successfully!")}
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                {t("Your")} <span className="font-medium">{createdAccount?.label}</span> {t("account has been added to your dashboard.")}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-zinc-800 rounded-lg">
            <div className="p-2 bg-white dark:bg-zinc-900 rounded-lg shadow-sm">
              <PlatformIcon slug={selectedPlatform?.slug} size={24} />
            </div>
            <div className="text-left">
              <p className="font-medium text-gray-900 dark:text-gray-100">
                {createdAccount?.label}
              </p>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {selectedPlatform?.name} Account
              </p>
            </div>
          </div>

          <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
            <div className="flex items-start gap-3">
              <Users className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" />
              <div className="text-left flex-1">
                <h4 className="text-sm font-medium text-blue-900 dark:text-blue-300 mb-1">
                  {t("What's Next?")}
                </h4>
                <p className="text-xs text-blue-700 dark:text-blue-400">
                  {t("You can connect this account now to start posting, or do it later from your Platform settings.")}
                </p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              onClick={handleConnectLater}
              className="flex-1"
            >
              <Clock className="w-4 h-4 mr-2" />
              {t("Connect Later")}
            </Button>
            <Button
              onClick={handleConnectNow}
              className="flex-1 bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              {t("Connect Now")}
            </Button>
          </div>
        </div>
      );
    }

    // Platform Selection View
    if (!selectedPlatform) {
      return (
        <div className="space-y-4">
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
            {t("Select a platform to connect your social media account")}
          </p>

          <div className="grid grid-cols-2 gap-3 max-h-[400px] min-h-[200px] overflow-y-auto pr-2 scroll-smooth">
            {platforms.map((platform) => (
              <button
                key={platform.id}
                onClick={() => handlePlatformSelect(platform)}
                className="flex items-center gap-3 p-4 bg-gray-50 dark:bg-zinc-800 hover:bg-gray-100 dark:hover:bg-zinc-700 rounded-lg border border-gray-200 dark:border-zinc-800 hover:border-gray-300 dark:hover:border-zinc-600 transition-colors duration-200 text-left group hover:shadow-sm"
              >
                <div className="p-2 bg-white dark:bg-zinc-900 rounded-lg shadow-sm group-hover:shadow-md transition-shadow duration-200">
                  <PlatformIcon slug={platform.slug} size={24} />
                </div>
                <div className="flex-1">
                  <h4 className="font-medium text-gray-900 dark:text-gray-100">
                    {platform.name}
                  </h4>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                    {platform.accountCount || 0} connected
                  </p>
                </div>
                <ChevronRight className="w-4 h-4 text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-300 transition-colors duration-200" />
              </button>
            ))}
          </div>

          <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
            <div className="flex items-start gap-3">
              <Sparkles className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" />
              <div className="flex-1">
                <h4 className="text-sm font-medium text-blue-900 dark:text-blue-300 mb-1">
                  {t("Pro Tip")}
                </h4>
                <p className="text-xs text-blue-700 dark:text-blue-400">
                  {t("Connect multiple accounts from the same platform to manage different brands or profiles.")}
                </p>
              </div>
            </div>
          </div>
        </div>
      );
    }

    // Account Name Input View
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-zinc-800 rounded-lg">
          <div className="p-2 bg-white dark:bg-zinc-900 rounded-lg shadow-sm">
            <PlatformIcon slug={selectedPlatform.slug} size={32} />
          </div>
          <div>
            <h4 className="font-medium text-gray-900 dark:text-gray-100">
              {selectedPlatform.name}
            </h4>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {t("Enter a name to identify this account")}
            </p>
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="account-name">
            {t("Account Name")} <span className="text-red-500">*</span>
          </Label>
          <Input
            id="account-name"
            type="text"
            value={accountName}
            onChange={(e) => setAccountName(e.target.value)}
            placeholder={t("e.g., Personal Account, Business Page, Brand X")}
            className="w-full"
            autoFocus
          />
          <p className="text-xs text-gray-500 dark:text-gray-400">
            {t("This name helps you identify the account in your dashboard")}
          </p>
        </div>

        <div className="p-4 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800">
          <div className="flex items-start gap-3">
            <Users className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5" />
            <div className="flex-1">
              <h4 className="text-sm font-medium text-amber-900 dark:text-amber-300 mb-1">
                {t("Authorization Required")}
              </h4>
              <p className="text-xs text-amber-700 dark:text-amber-400">
                {t("You'll be redirected to")} {selectedPlatform.name} {t("to authorize access to your account.")}
              </p>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <Button
            variant="outline"
            onClick={handleBack}
            disabled={isConnecting}
            className="flex-1"
          >
            {t("Back")}
          </Button>
          <Button
            onClick={handleCreateAccount}
            disabled={!accountName.trim() || isConnecting}
            isLoading={isConnecting}
            className="flex-1 bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
          >
            {isConnecting ? t("Creating Account...") : t("Create Account")}
          </Button>
        </div>
      </div>
    );
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleModalClose}
      title={getModalTitle()}
      showSubmit={false}
      size="xl"
    >
      {renderContent()}
    </Modal>
  );
}