import React, { useCallback } from 'react';
import DeploymentOptions from './DeploymentOptions';
import DomainConfiguration from './DomainConfiguration';
import { Toast } from '../shared/Toast';
import { TemplatePreview } from '../shared/TemplatePreview';

// Custom hooks
import useDeploymentConfig from '../../hooks/useDeploymentConfig';
import useDomainConfig from '../../hooks/useDomainConfig';
import useDnsVerification from '../../hooks/useDnsVerification';
import useToast from '../../hooks/useToast';
import useFormValidation from '../../hooks/useFormValidation';

/**
 * Main DomainSetupForm component
 * @param {Object} props - Component props
 * @param {string} props.defaultSubdomain - Default SiliconPin subdomain
 * @returns {JSX.Element} - Rendered component
 */
export const DomainSetupForm = ({ defaultSubdomain }) => {
  // Initialize hooks for different concerns
  const { toast, showToast } = useToast();

  // Deployment configuration
  const deploymentConfig = useDeploymentConfig();

  // DNS verification (depends on domain config for reset logic)
  const dnsVerificationHook = useDnsVerification(showToast);
  const { dnsVerified, checkDnsConfig, resetAllDnsVerification } = dnsVerificationHook;

  // Domain configuration (needs DNS reset function)
  const domainConfig = useDomainConfig({}, resetAllDnsVerification);

  // Pass the domain config to DNS verification hook for dependency tracking
  // This is done after initialization to avoid circular dependencies
  dnsVerificationHook.domainConfig = domainConfig.config;

  // Form validation based on domain and DNS state
  const { formValid } = useFormValidation(
    domainConfig.config,
    domainConfig.validation,
    dnsVerified
  );

  // Form submission handler
  const handleSubmit = useCallback((e) => {
    e.preventDefault();

    if (domainConfig.useCustomDomain && !formValid) {
      showToast('Please complete domain validation and DNS verification before deploying.');
      return;
    }

    // In a real app, this would submit the form data to the server
    console.log({
      deploymentType: deploymentConfig.type,
      appType: deploymentConfig.appType,
      sampleWebAppType: deploymentConfig.sampleWebAppType,
      sourceType: deploymentConfig.sourceType,
      repoUrl: deploymentConfig.repoUrl,
      deploymentKey: deploymentConfig.deploymentKey,
      useSubdomain: domainConfig.useSubdomain,
      useCustomDomain: domainConfig.useCustomDomain,
      customDomain: domainConfig.customDomain,
      customSubdomain: domainConfig.customSubdomain,
      domainType: domainConfig.domainType,
      dnsMethod: domainConfig.dnsMethod
    });

    showToast('Form submitted successfully!');
  }, [
    formValid,
    showToast,
    deploymentConfig,
    domainConfig
  ]);

  return (
    <div className="bg-neutral-800 rounded-lg p-6 sm:p-8 border border-neutral-700">
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Deployment Options Section */}
        <DeploymentOptions
          deploymentConfig={deploymentConfig}
          handlers={{
            handleDeploymentTypeChange: deploymentConfig.handleDeploymentTypeChange,
            handleAppTypeChange: deploymentConfig.handleAppTypeChange,
            handleSampleWebAppTypeChange: deploymentConfig.handleSampleWebAppTypeChange,
            handleSourceTypeChange: deploymentConfig.handleSourceTypeChange,
            handleRepoUrlChange: deploymentConfig.handleRepoUrlChange,
            handleDeploymentKeyChange: deploymentConfig.handleDeploymentKeyChange,
            handleFileChange: deploymentConfig.handleFileChange
          }}
          showToast={showToast}
          TemplatePreview={TemplatePreview}
        />

        {/* Domain Configuration Section */}
        <DomainConfiguration
          domainConfig={domainConfig.config}
          validation={domainConfig.validation}
          dnsVerified={dnsVerified}
          handlers={{
            handleUseSubdomainChange: domainConfig.handleUseSubdomainChange,
            handleUseCustomDomainChange: domainConfig.handleUseCustomDomainChange,
            handleDomainTypeChange: domainConfig.handleDomainTypeChange,
            handleDnsMethodChange: domainConfig.handleDnsMethodChange,
            handleDomainChange: domainConfig.handleDomainChange,
            handleSubdomainChange: domainConfig.handleSubdomainChange,
            validateDomain: domainConfig.validateDomain
          }}
          checkDnsConfig={checkDnsConfig}
          defaultSubdomain={defaultSubdomain}
          showToast={showToast}
        />

        {/* Form Submit Button */}
        <button
          type="submit"
          disabled={domainConfig.useCustomDomain && !formValid}
          className={`w-full mt-6 px-6 py-3 text-white font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-neutral-800
            ${domainConfig.useCustomDomain && !formValid
            ? 'bg-neutral-600 cursor-not-allowed'
            : 'bg-[#6d9e37] hover:bg-[#598035] focus:ring-[#6d9e37] transition-colors'
          }`}
          aria-label="Start deployment"
        >
          Start the Deployment
        </button>
      </form>

      <Toast visible={toast.visible} message={toast.message} />
    </div>
  );
};

export default DomainSetupForm;