import { useEffect, useState } from "react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Settings, Palette, Users, Loader2, MailCheck, Crown, SlidersHorizontal, Mails } from "lucide-react"
import { toast } from "sonner"
import { FeatureHeader } from "@/components/feature-header"
import { useEmailVerification } from "../hooks/use-email-verification"
import { SettingsTab } from "./tabs/settings-tab"
import { CustomizationTab } from "./tabs/customization-tab"
import { VerificationEmailTab } from "./tabs/verification-email-tab"
import { PendingUsersTab } from "./tabs/pending-users-tab"
import { EmailVerificationUpgradeTab } from "./tabs/upgrade-tab"
import { AdvancedTab } from "./tabs/advanced-tab"
import { usePro } from "@/contexts/pro-context"
import { defaultSettings } from "../config"

const EMAIL_VERIFICATION_DOCS_URL = "https://www.swiftcommerce.io/help/spam/email-verification/"

export function EmailVerificationSettings() {
  const { isPro } = usePro()
  const { 
    settings, 
    updateSettings, 
    toggleRole,
    saveSettings, 
    saving, 
    loading,
    hasChanges,
  } = useEmailVerification()

  const [activeTab, setActiveTab] = useState("settings")

  useEffect(() => {
    if (!isPro && ['advanced', 'emails', 'pending-users'].includes(activeTab)) {
      setActiveTab('settings')
    } else if (activeTab === 'emails' && settings.verificationMode !== 'admin_approval') {
      setActiveTab('advanced')
    }
  }, [activeTab, isPro, settings.verificationMode])

  const handleSave = async () => {
    const result = await saveSettings()
    if (result.success) {
      toast.success("Settings saved", {
        description: "Your email verification settings have been saved successfully."
      })
    } else {
      toast.error("Failed to save settings", {
        description: "Please try again or check your connection."
      })
    }
  }

  const handleReset = () => {
    // Reset to defaults
    Object.keys(defaultSettings).forEach(key => {
      updateSettings(key as keyof typeof defaultSettings, defaultSettings[key as keyof typeof defaultSettings])
    })
    toast.success("Settings reset", {
      description: "All settings have been reset to their defaults. Don't forget to save."
    })
  }

  if (loading) {
    return (
      <div className="flex flex-1 items-center justify-center p-6">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
          <p className="mt-4 text-sm text-muted-foreground">Loading settings...</p>
        </div>
      </div>
    )
  }

  return (
    <FeatureHeader
      icon={<MailCheck className="h-6 w-6" />}
      title="Email Verification"
      description="Require users to verify their email address before accessing your site"
      documentationUrl={EMAIL_VERIFICATION_DOCS_URL}
      enabled={settings.enabled}
      onEnabledChange={(checked) => updateSettings('enabled', checked)}
      hasChanges={hasChanges}
      isSaving={saving}
      onSave={handleSave}
      onReset={handleReset}
    >
      <div className="flex flex-col gap-6">
        {/* Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList>
            <TabsTrigger value="settings" className="gap-2">
              <Settings className="h-4 w-4" />
              Settings
            </TabsTrigger>
            <TabsTrigger value="customization" className="gap-2">
              <Palette className="h-4 w-4" />
              Appearance
            </TabsTrigger>
            {isPro && (
              <TabsTrigger value="advanced" className="gap-2">
                <SlidersHorizontal className="h-4 w-4" />
                Advanced
              </TabsTrigger>
            )}
            {isPro && settings.verificationMode === 'admin_approval' && (
              <TabsTrigger value="emails" className="gap-2">
                <Mails className="h-4 w-4" />
                Approval Emails
              </TabsTrigger>
            )}
            {isPro && (
              <TabsTrigger value="pending-users" className="gap-2">
                <Users className="h-4 w-4" />
                Pending Users
              </TabsTrigger>
            )}
            {!isPro && (
              <TabsTrigger
                value="upgrade"
                className="gap-2 text-white hover:text-white data-[state=active]:text-white data-[state=active]:shadow-none"
                style={{ backgroundColor: '#00226b' }}
              >
                <Crown className="h-4 w-4" />
                Upgrade to Pro
              </TabsTrigger>
            )}
          </TabsList>

          <TabsContent value="settings" className="mt-6">
            <SettingsTab 
              settings={settings} 
              updateSettings={updateSettings}
              toggleRole={toggleRole}
            />
          </TabsContent>

          <TabsContent value="customization" className="mt-6">
            <VerificationEmailTab
              settings={settings}
              updateSettings={updateSettings}
            />
          </TabsContent>

          {isPro && (
            <TabsContent value="advanced" className="mt-6">
              <AdvancedTab settings={settings} updateSettings={updateSettings} />
            </TabsContent>
          )}

          {isPro && settings.verificationMode === 'admin_approval' && (
            <TabsContent value="emails" className="mt-6">
              <CustomizationTab settings={settings} updateSettings={updateSettings} />
            </TabsContent>
          )}

          {isPro && (
            <TabsContent value="pending-users" className="mt-6">
              <PendingUsersTab verificationMode={settings.verificationMode} />
            </TabsContent>
          )}

          {!isPro && (
            <TabsContent value="upgrade" className="mt-6">
              <EmailVerificationUpgradeTab />
            </TabsContent>
          )}
        </Tabs>
      </div>
    </FeatureHeader>
  )
}
