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 { ShoppingCart, KeyRound } from "lucide-react"
import { SettingsGrid } from "@/components/settings-layout"
import {
  EmailVerificationSettings,
  wordpressRoles,
} 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 [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.enableForRegistration || settings.enableForWooCommerceRegistration)

  return (
    <SettingsGrid>
      {/* 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 during registration, so the account is ready after verification or approval.
              </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>

        </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>

    </SettingsGrid>
  )
}
