import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { ShoppingCart, ExternalLink, KeyRound } from "lucide-react"
import { SettingsGrid } from "@/components/settings-layout"
import { usePro } from "@/contexts/pro-context"
import { ProIndicator } from "@/components/pro/pro-indicator"
import { Input } from "@/components/ui/input"
import { 
  EmailVerificationSettings, 
  expiryOptions, 
  autoDeleteOptions,
  resendLimitOptions,
  wordpressRoles,
  verificationModeOptions,
} from "../../config"

interface SettingsTabProps {
  settings: EmailVerificationSettings
  updateSettings: <K extends keyof EmailVerificationSettings>(key: K, value: EmailVerificationSettings[K]) => void
  toggleRole: (role: string) => void
}

interface RegistrationFormState {
  enabled: boolean
  applyToWordPress: boolean
  applyToWooCommerce: boolean
}

export function SettingsTab({ settings, updateSettings, toggleRole }: SettingsTabProps) {
  const { isPro } = usePro()
  const [registrationForm, setRegistrationForm] = useState<RegistrationFormState>({
    enabled: false,
    applyToWordPress: false,
    applyToWooCommerce: false,
  })

  useEffect(() => {
    const loadRegistrationFormSettings = async () => {
      try {
        const apiUrl = window.swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
        const response = await fetch(`${apiUrl}/registration-form/settings`, {
          headers: {
            'X-WP-Nonce': window.swiftCommerceData?.restNonce || '',
          },
          credentials: 'same-origin',
        })

        if (!response.ok) return

        const data = await response.json()
        if (data.success && data.settings) {
          setRegistrationForm({
            enabled: Boolean(data.settings.enabled),
            applyToWordPress: Boolean(data.settings.applyToWordPress),
            applyToWooCommerce: Boolean(data.settings.applyToWooCommerce),
          })
        }
      } catch (error) {
        console.error('Failed to load registration form status:', error)
      }
    }

    loadRegistrationFormSettings()
  }, [])

  const hasRegistrationFormConflict =
    settings.enabled &&
    registrationForm.enabled &&
    (
      (settings.enableForRegistration && registrationForm.applyToWordPress) ||
      (settings.enableForWooCommerceRegistration && registrationForm.applyToWooCommerce)
    )

  const showsPasswordFlowNotice =
    settings.enabled &&
    settings.verificationMode === 'email_verification' &&
    (settings.enableForRegistration || settings.enableForWooCommerceRegistration)

  return (
    <SettingsGrid>
      {/* Verification Mode - FREE shows Email Verification only, Pro adds Admin Approval */}
      <Card>
        <CardHeader>
          <CardTitle>Verification Mode</CardTitle>
          <CardDescription>
            Choose how new user registrations are verified
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {verificationModeOptions.map((mode) => {
              const isAdminApproval = mode.value === 'admin_approval'
              // Hide Admin Approval option entirely for Free users
              if (isAdminApproval && !isPro) return null
              
              const isSelected = settings.verificationMode === mode.value
              return (
                <div
                  key={mode.value}
                  className={`
                    flex items-center gap-4 rounded-lg border p-4 transition-colors cursor-pointer
                    ${isSelected ? 'border-primary bg-primary/5' : 'hover:border-muted-foreground/50'}
                  `}
                  onClick={() => updateSettings('verificationMode', mode.value as EmailVerificationSettings['verificationMode'])}
                >
                  <div className={`flex h-4 w-4 items-center justify-center rounded-full border-2 ${isSelected ? 'border-primary' : 'border-muted-foreground/40'}`}>
                    {isSelected && <div className="h-2 w-2 rounded-full bg-primary" />}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-sm">{mode.label}</span>
                      {isAdminApproval && <ProIndicator size="sm" />}
                    </div>
                    <p className="text-sm text-muted-foreground">{mode.description}</p>
                  </div>
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>

      {/* Core Settings - FREE */}
      <Card>
        <CardHeader>
          <CardTitle>Verification Settings</CardTitle>
          <CardDescription>
            Configure when email verification is required
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {hasRegistrationFormConflict && (
            <div className="rounded-lg border p-4 space-y-3">
              <div className="flex items-center justify-between gap-4">
                <div className="space-y-0.5">
                  <Label className="text-base font-medium">Registration Form controls fields</Label>
                  <p className="text-sm text-muted-foreground">
                    When enabled, Registration Form field order and custom fields appear on active registration forms. When disabled, Email Verification shows its default password setup fields.
                  </p>
                </div>
                <Switch
                  checked={settings.registrationFormMode === 'registration_form'}
                  onCheckedChange={(checked) => updateSettings('registrationFormMode', checked ? 'registration_form' : 'email_verification')}
                />
              </div>
              <p className="text-sm text-muted-foreground">
                Active form: {settings.registrationFormMode === 'registration_form' ? 'Registration Form fields' : 'Email Verification default fields'}
              </p>
            </div>
          )}

          {showsPasswordFlowNotice && (
            <Alert>
              <KeyRound className="h-4 w-4" />
              <AlertTitle>Password setup is handled during registration</AlertTitle>
              <AlertDescription>
                Swift Commerce asks new users to create their password before sending the verification email. After they verify their email, they can log in with that password.
              </AlertDescription>
            </Alert>
          )}

          {/* Enable for WordPress Registration - FREE */}
          <div className="flex items-center justify-between rounded-lg border p-4">
            <div className="space-y-0.5">
              <Label className="text-base font-medium">WordPress Registration</Label>
              <p className="text-sm text-muted-foreground">
                Require email verification for WordPress default registration form
              </p>
            </div>
            <Switch
              checked={settings.enableForRegistration}
              onCheckedChange={(checked) => updateSettings('enableForRegistration', checked)}
            />
          </div>

          {/* Enable for WooCommerce My Account - FREE */}
          <div className="flex items-center justify-between rounded-lg border p-4">
            <div className="space-y-0.5">
              <div className="flex items-center gap-2">
                <Label className="text-base font-medium">WooCommerce My Account</Label>
                <Badge variant="outline" className="text-xs">
                  <ShoppingCart className="h-3 w-3 mr-1" />
                  WooCommerce
                </Badge>
              </div>
              <p className="text-sm text-muted-foreground">
                Require email verification for WooCommerce My Account registration
              </p>
            </div>
            <Switch
              checked={settings.enableForWooCommerceRegistration}
              onCheckedChange={(checked) => updateSettings('enableForWooCommerceRegistration', checked)}
            />
          </div>

          {/* Enable for Logged-in Checkout - Pro only, hidden for Free */}
          {isPro && (
            <div className="flex items-center justify-between rounded-lg border p-4">
              <div className="space-y-0.5">
                <div className="flex items-center gap-2">
                  <Label className="text-base font-medium">Logged-in Checkout</Label>
                  <Badge variant="outline" className="text-xs">WooCommerce</Badge>
                  <ProIndicator size="sm" />
                </div>
                <p className="text-sm text-muted-foreground">
                  Require email verification for logged-in users at checkout
                </p>
              </div>
              <Switch
                checked={settings.enableForLoggedInCheckout}
                onCheckedChange={(checked) => updateSettings('enableForLoggedInCheckout', checked)}
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* Skip Roles - FREE */}
      <Card>
        <CardHeader>
          <CardTitle>Skip Verification for Roles</CardTitle>
          <CardDescription>
            Select user roles that should bypass email verification
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {wordpressRoles.map((role) => {
              const isChecked = settings.skipRoles.includes(role.value)
              return (
                <div
                  key={role.value}
                  className={`
                    flex items-center gap-3 rounded-lg border p-3 transition-colors cursor-pointer
                    ${isChecked ? 'border-primary bg-primary/5' : 'hover:border-muted-foreground/50'}
                  `}
                  onClick={() => toggleRole(role.value)}
                >
                  <Checkbox
                    id={`role-${role.value}`}
                    checked={isChecked}
                    onCheckedChange={() => toggleRole(role.value)}
                  />
                  <Label htmlFor={`role-${role.value}`} className="flex-1 cursor-pointer">
                    {role.label}
                  </Label>
                </div>
              )
            })}
          </div>
          <p className="text-sm text-muted-foreground mt-4">
            Users with selected roles will not need to verify their email address.
          </p>
        </CardContent>
      </Card>

      {/* Link Settings - Pro only, hidden for Free */}
      {isPro && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              Link & Limits
              <ProIndicator size="sm" />
            </CardTitle>
            <CardDescription>
              Configure verification link expiry and limits
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Link Expiry */}
            <div className="grid gap-2">
              <Label htmlFor="link-expiry">Verification Link Expiry</Label>
              <Select
                value={settings.linkExpiry}
                onValueChange={(value) => updateSettings('linkExpiry', value)}
              >
                <SelectTrigger id="link-expiry" className="w-full max-w-xs">
                  <SelectValue placeholder="Select expiry time" />
                </SelectTrigger>
                <SelectContent>
                  {expiryOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-sm text-muted-foreground">
                How long the verification link remains valid
              </p>
            </div>

            {/* Resend Limit */}
            <div className="grid gap-2">
              <Label htmlFor="resend-limit">Resend Email Limit</Label>
              <Select
                value={settings.resendLimit}
                onValueChange={(value) => updateSettings('resendLimit', value)}
              >
                <SelectTrigger id="resend-limit" className="w-full max-w-xs">
                  <SelectValue placeholder="Select resend limit" />
                </SelectTrigger>
                <SelectContent>
                  {resendLimitOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-sm text-muted-foreground">
                Maximum number of times a user can request a new verification email
              </p>
            </div>

            {/* Auto Delete */}
            <div className="grid gap-2">
              <Label htmlFor="auto-delete">Auto-delete Unverified Users</Label>
              <Select
                value={settings.autoDeleteAfter}
                onValueChange={(value) => updateSettings('autoDeleteAfter', value)}
              >
                <SelectTrigger id="auto-delete" className="w-full max-w-xs">
                  <SelectValue placeholder="Select auto-delete time" />
                </SelectTrigger>
                <SelectContent>
                  {autoDeleteOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-sm text-muted-foreground">
                Automatically delete users who don't verify their email within this time
              </p>
            </div>

            {/* Redirect After Verification */}
            <div className="grid gap-2">
              <Label htmlFor="redirect-url" className="flex items-center gap-2">
                <ExternalLink className="h-4 w-4" />
                Redirect After Verification
              </Label>
              <Input
                id="redirect-url"
                type="url"
                placeholder="Leave empty for default (login page)"
                className="w-full max-w-md"
                value={settings.redirectAfterVerification}
                onChange={(e) => updateSettings('redirectAfterVerification', e.target.value)}
              />
              <p className="text-sm text-muted-foreground">
                Custom URL to redirect users to after they verify their email. Leave empty to use the default login or My Account page.
              </p>
            </div>
          </CardContent>
        </Card>
      )}
    </SettingsGrid>
  )
}
