import { Eye, EyeOff, Shield, MousePointer, Fingerprint, Crown } from "lucide-react"
import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Slider } from "@/components/ui/slider"
import { Badge } from "@/components/ui/badge"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { 
  RecaptchaState, 
  CaptchaProvider,
  RecaptchaVersion, 
  RecaptchaV2Mode, 
  RecaptchaV3Display,
  TurnstileAppearance,
  HcaptchaMode,
  recaptchaVersions 
} from "../../config"

interface GeneralTabProps {
  settings: RecaptchaState
  updateSettings: <K extends keyof RecaptchaState>(key: K, value: RecaptchaState[K]) => void
  setProvider: (provider: CaptchaProvider) => void
  setVersion: (version: RecaptchaVersion) => void
  setV2Mode: (mode: RecaptchaV2Mode) => void
  setV3Display: (display: RecaptchaV3Display) => void
  isPro: boolean
}

// Get plugin URL for local assets
const getPluginUrl = () => {
  return window.swiftCommerceData?.pluginUrl || '/wp-content/plugins/swift-commerce/'
}

// Provider definitions
interface ProviderOption {
  id: CaptchaProvider
  name: string
  logo: string
  isPro: boolean
}

const getProviders = (): ProviderOption[] => [
  {
    id: 'google-recaptcha',
    name: 'Google reCAPTCHA',
    logo: `${getPluginUrl()}assets/img/icons/google-recaptcha.png`,
    isPro: false,
  },
  {
    id: 'cloudflare-turnstile',
    name: 'Cloudflare Turnstile',
    logo: `${getPluginUrl()}assets/img/icons/cloudflare-turnstile.png`,
    isPro: true,
  },
  {
    id: 'hcaptcha',
    name: 'hCaptcha',
    logo: `${getPluginUrl()}assets/img/icons/hcaptcha.png`,
    isPro: true,
  },
]

export function GeneralTab({ 
  settings, 
  updateSettings, 
  setProvider,
  setVersion, 
  setV2Mode, 
  setV3Display,
  isPro,
}: GeneralTabProps) {
  const [showV2SecretKey, setShowV2SecretKey] = useState(false)
  const [showV3SecretKey, setShowV3SecretKey] = useState(false)
  const [showTurnstileSecretKey, setShowTurnstileSecretKey] = useState(false)
  const [showHcaptchaSecretKey, setShowHcaptchaSecretKey] = useState(false)

  const hasProvider = settings.provider !== ''

  // Free users only see Google reCAPTCHA; Pro users see all
  const providers = getProviders().filter(p => !p.isPro || isPro)

  return (
    <div className="space-y-6">

      {/* Step 1: Choose CAPTCHA Provider */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            CAPTCHA Provider
          </CardTitle>
          <CardDescription>
            Choose which CAPTCHA service to use for bot protection on your site.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="max-w-sm">
            <Select
              value={settings.provider || '__none__'}
              onValueChange={(value) => setProvider((value === '__none__' ? '' : value) as CaptchaProvider)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Choose a provider" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__none__">
                  <span className="text-muted-foreground">Choose a provider</span>
                </SelectItem>
                {providers.map((provider) => (
                  <SelectItem key={provider.id} value={provider.id}>
                    <span className="flex items-center gap-2">
                      <img
                        src={provider.logo}
                        alt=""
                        className="h-4 w-4 shrink-0 object-contain"
                      />
                      <span>{provider.name}</span>
                      {provider.isPro && (
                        <Crown className="h-3.5 w-3.5 shrink-0" style={{ color: '#002269' }} />
                      )}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {!isPro && (
              <p className="mt-2 text-xs text-muted-foreground">
                More providers are available with Pro.
              </p>
            )}
          </div>
        </CardContent>
      </Card>

      {/* ── Google reCAPTCHA configuration ── */}
      {hasProvider && settings.provider === 'google-recaptcha' && (
        <>
          {/* Step 2: Choose reCAPTCHA Version */}
          <Card>
            <CardHeader>
              <CardTitle>reCAPTCHA Version</CardTitle>
              <CardDescription>
                Each version uses different API keys. You'll need to{' '}
                <a 
                  href="https://www.google.com/recaptcha/admin/create" 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="text-primary underline"
                >
                  register your site
                </a>{' '}
                with the version you choose.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <RadioGroup
                value={settings.version}
                onValueChange={(value) => setVersion(value as RecaptchaVersion)}
                className="grid grid-cols-1 sm:grid-cols-2 gap-3"
              >
                {/* v2 Option */}
                <div className="relative">
                  <RadioGroupItem
                    value="v2"
                    id="version-v2"
                    className="peer sr-only"
                  />
                  <Label
                    htmlFor="version-v2"
                    className="flex flex-col gap-2 rounded-lg border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 cursor-pointer transition-all"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <MousePointer className="h-4 w-4" />
                        <span className="font-semibold text-sm">{recaptchaVersions.v2.name}</span>
                      </div>
                      <Badge variant="outline" className="text-xs">Challenge</Badge>
                    </div>
                    <span className="text-xs text-muted-foreground">
                      {recaptchaVersions.v2.description}
                    </span>
                  </Label>
                </div>

                {/* v3 Option */}
                <div className="relative">
                  <RadioGroupItem
                    value="v3"
                    id="version-v3"
                    className="peer sr-only"
                  />
                  <Label
                    htmlFor="version-v3"
                    className="flex flex-col gap-2 rounded-lg border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 cursor-pointer transition-all"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Fingerprint className="h-4 w-4" />
                        <span className="font-semibold text-sm">{recaptchaVersions.v3.name}</span>
                      </div>
                      <Badge variant="outline" className="text-xs">Score-based</Badge>
                    </div>
                    <span className="text-xs text-muted-foreground">
                      {recaptchaVersions.v3.description}
                    </span>
                  </Label>
                </div>
              </RadioGroup>
            </CardContent>
          </Card>

          {/* Step 3: API Keys */}
          <Card>
            <CardHeader>
              <CardTitle>API Keys</CardTitle>
              <CardDescription>
                Enter your reCAPTCHA {settings.version.toUpperCase()} keys from the{' '}
                <a 
                  href="https://www.google.com/recaptcha/admin/create" 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="text-primary underline"
                >
                  Google reCAPTCHA Admin Console
                </a>
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {settings.version === 'v2' && (
                <>
                  <div className="space-y-2">
                    <Label htmlFor="v2-site-key">Site Key</Label>
                    <Input
                      id="v2-site-key"
                      type="text"
                      placeholder="Enter your v2 site key"
                      value={settings.v2SiteKey}
                      onChange={(e) => updateSettings('v2SiteKey', e.target.value)}
                    />
                    <p className="text-xs text-muted-foreground">
                      This key is used to display the reCAPTCHA widget on your site.
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="v2-secret-key">Secret Key</Label>
                    <div className="relative">
                      <Input
                        id="v2-secret-key"
                        type={showV2SecretKey ? "text" : "password"}
                        placeholder="Enter your v2 secret key"
                        value={settings.v2SecretKey}
                        onChange={(e) => updateSettings('v2SecretKey', e.target.value)}
                        className="pr-10"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => setShowV2SecretKey(!showV2SecretKey)}
                      >
                        {showV2SecretKey ? (
                          <EyeOff className="h-4 w-4 text-muted-foreground" />
                        ) : (
                          <Eye className="h-4 w-4 text-muted-foreground" />
                        )}
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      This key is used for server-side verification of responses.
                    </p>
                  </div>
                </>
              )}

              {settings.version === 'v3' && (
                <>
                  <div className="space-y-2">
                    <Label htmlFor="v3-site-key">Site Key</Label>
                    <Input
                      id="v3-site-key"
                      type="text"
                      placeholder="Enter your v3 site key"
                      value={settings.v3SiteKey}
                      onChange={(e) => updateSettings('v3SiteKey', e.target.value)}
                    />
                    <p className="text-xs text-muted-foreground">
                      This key is used to load the reCAPTCHA script on your site.
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="v3-secret-key">Secret Key</Label>
                    <div className="relative">
                      <Input
                        id="v3-secret-key"
                        type={showV3SecretKey ? "text" : "password"}
                        placeholder="Enter your v3 secret key"
                        value={settings.v3SecretKey}
                        onChange={(e) => updateSettings('v3SecretKey', e.target.value)}
                        className="pr-10"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => setShowV3SecretKey(!showV3SecretKey)}
                      >
                        {showV3SecretKey ? (
                          <EyeOff className="h-4 w-4 text-muted-foreground" />
                        ) : (
                          <Eye className="h-4 w-4 text-muted-foreground" />
                        )}
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      This key is used for server-side score verification.
                    </p>
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          {/* Step 4: Version-specific Configuration */}
          {settings.version === 'v2' && (
            <Card>
              <CardHeader>
                <CardTitle>Challenge Type</CardTitle>
                <CardDescription>
                  Select how the reCAPTCHA challenge appears to users.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <RadioGroup
                  value={settings.v2Mode}
                  onValueChange={(value) => setV2Mode(value as RecaptchaV2Mode)}
                  className="grid gap-3"
                >
                  {recaptchaVersions.v2.modes.map((mode) => (
                    <div 
                      key={mode.id} 
                      className={`
                        flex items-start space-x-3 rounded-lg border p-4 cursor-pointer transition-colors
                        ${settings.v2Mode === mode.id ? 'border-primary bg-primary/5' : 'border-muted hover:border-muted-foreground/50'}
                      `}
                      onClick={() => setV2Mode(mode.id as RecaptchaV2Mode)}
                    >
                      <RadioGroupItem value={mode.id} id={`v2-${mode.id}`} className="mt-1" />
                      <div className="space-y-1 flex-1">
                        <Label htmlFor={`v2-${mode.id}`} className="font-medium cursor-pointer">
                          {mode.name}
                        </Label>
                        <p className="text-sm text-muted-foreground">
                          {mode.description}
                        </p>
                      </div>
                    </div>
                  ))}
                </RadioGroup>
              </CardContent>
            </Card>
          )}

          {settings.version === 'v3' && (
            <>
              {/* V3 Score Threshold */}
              <Card>
                <CardHeader>
                  <CardTitle>Score Threshold</CardTitle>
                  <CardDescription>
                    Set the minimum score required to pass verification. Higher values are stricter.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <Label>Threshold Score</Label>
                    <span className="text-lg font-semibold tabular-nums">{settings.v3Threshold.toFixed(1)}</span>
                  </div>
                  <Slider
                    value={[settings.v3Threshold]}
                    onValueChange={([value]) => updateSettings('v3Threshold', value)}
                    min={0}
                    max={1}
                    step={0.1}
                    className="w-full"
                  />
                  <div className="flex justify-between text-xs text-muted-foreground">
                    <span>0.0 — Likely Bot</span>
                    <span>0.5 — Recommended</span>
                    <span>1.0 — Likely Human</span>
                  </div>
                  <div className="rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground">
                    <strong>Tip:</strong> Start with 0.5 and adjust based on your needs. Lower the threshold if legitimate users are being blocked.
                  </div>
                </CardContent>
              </Card>

              {/* V3 Badge Display */}
              <Card>
                <CardHeader>
                  <CardTitle>Badge Display</CardTitle>
                  <CardDescription>
                    Choose how the reCAPTCHA badge is displayed on your site.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <RadioGroup
                    value={settings.v3Display}
                    onValueChange={(value) => setV3Display(value as RecaptchaV3Display)}
                    className="grid gap-3"
                  >
                    {recaptchaVersions.v3.displayOptions.map((option) => (
                      <div 
                        key={option.id} 
                        className={`
                          flex items-start space-x-3 rounded-lg border p-4 cursor-pointer transition-colors
                          ${settings.v3Display === option.id ? 'border-primary bg-primary/5' : 'border-muted hover:border-muted-foreground/50'}
                        `}
                        onClick={() => setV3Display(option.id as RecaptchaV3Display)}
                      >
                        <RadioGroupItem value={option.id} id={`v3-${option.id}`} className="mt-1" />
                        <div className="space-y-1 flex-1">
                          <Label htmlFor={`v3-${option.id}`} className="font-medium cursor-pointer">
                            {option.name}
                          </Label>
                          <p className="text-sm text-muted-foreground">
                            {option.description}
                          </p>
                        </div>
                      </div>
                    ))}
                  </RadioGroup>

                  {settings.v3Display === 'hidden' && (
                    <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-800">
                      <strong>Note:</strong> When hiding the badge, you must include reCAPTCHA branding in your privacy policy.
                    </div>
                  )}
                </CardContent>
              </Card>
            </>
          )}
        </>
      )}

      {/* ── Cloudflare Turnstile configuration (Pro only) ── */}
      {hasProvider && settings.provider === 'cloudflare-turnstile' && isPro && (
        <Card>
          <CardHeader>
            <CardTitle>Turnstile API Keys</CardTitle>
            <CardDescription>
              Enter your Cloudflare Turnstile keys from the{' '}
              <a 
                href="https://dash.cloudflare.com/?to=/:account/turnstile" 
                target="_blank" 
                rel="noopener noreferrer"
                className="text-primary underline"
              >
                Cloudflare Dashboard
              </a>
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="turnstile-site-key">Site Key</Label>
              <Input
                id="turnstile-site-key"
                type="text"
                placeholder="Enter your Turnstile site key"
                value={settings.turnstileSiteKey}
                onChange={(e) => updateSettings('turnstileSiteKey', e.target.value)}
              />
              <p className="text-xs text-muted-foreground">
                This key is used to render the Turnstile widget on your site.
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="turnstile-secret-key">Secret Key</Label>
              <div className="relative">
                <Input
                  id="turnstile-secret-key"
                  type={showTurnstileSecretKey ? "text" : "password"}
                  placeholder="Enter your Turnstile secret key"
                  value={settings.turnstileSecretKey}
                  onChange={(e) => updateSettings('turnstileSecretKey', e.target.value)}
                  className="pr-10"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                  onClick={() => setShowTurnstileSecretKey(!showTurnstileSecretKey)}
                >
                  {showTurnstileSecretKey ? (
                    <EyeOff className="h-4 w-4 text-muted-foreground" />
                  ) : (
                    <Eye className="h-4 w-4 text-muted-foreground" />
                  )}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                This key is used for server-side verification of responses.
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ── Turnstile Widget Mode (Pro only) ── */}
      {hasProvider && settings.provider === 'cloudflare-turnstile' && isPro && (
        <Card>
          <CardHeader>
            <CardTitle>Widget Mode</CardTitle>
            <CardDescription>
              Choose when the Turnstile widget is visible to users.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <RadioGroup
              value={settings.turnstileAppearance}
              onValueChange={(value) => updateSettings('turnstileAppearance', value as TurnstileAppearance)}
              className="space-y-3"
            >
              <div className="flex items-start space-x-3">
                <RadioGroupItem value="always" id="turnstile-always" className="mt-0.5" />
                <div>
                  <Label htmlFor="turnstile-always" className="font-medium">Always visible</Label>
                  <p className="text-xs text-muted-foreground">
                    The widget is always shown on the page. Best for transparency.
                  </p>
                </div>
              </div>
              <div className="flex items-start space-x-3">
                <RadioGroupItem value="execute" id="turnstile-execute" className="mt-0.5" />
                <div>
                  <Label htmlFor="turnstile-execute" className="font-medium">Execute</Label>
                  <p className="text-xs text-muted-foreground">
                    The widget is only shown when actively solving a challenge.
                  </p>
                </div>
              </div>
              <div className="flex items-start space-x-3">
                <RadioGroupItem value="interaction-only" id="turnstile-interaction" className="mt-0.5" />
                <div>
                  <Label htmlFor="turnstile-interaction" className="font-medium">Interaction only</Label>
                  <p className="text-xs text-muted-foreground">
                    Invisible to users — the widget only appears if interaction is needed.
                  </p>
                </div>
              </div>
            </RadioGroup>
          </CardContent>
        </Card>
      )}

      {/* ── hCaptcha configuration (Pro only) ── */}
      {hasProvider && settings.provider === 'hcaptcha' && isPro && (
        <Card>
          <CardHeader>
            <CardTitle>hCaptcha API Keys</CardTitle>
            <CardDescription>
              Enter your hCaptcha keys from the{' '}
              <a 
                href="https://dashboard.hcaptcha.com/sites" 
                target="_blank" 
                rel="noopener noreferrer"
                className="text-primary underline"
              >
                hCaptcha Dashboard
              </a>
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="hcaptcha-site-key">Site Key</Label>
              <Input
                id="hcaptcha-site-key"
                type="text"
                placeholder="Enter your hCaptcha site key"
                value={settings.hcaptchaSiteKey}
                onChange={(e) => updateSettings('hcaptchaSiteKey', e.target.value)}
              />
              <p className="text-xs text-muted-foreground">
                This key is used to render the hCaptcha widget on your site.
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="hcaptcha-secret-key">Secret Key</Label>
              <div className="relative">
                <Input
                  id="hcaptcha-secret-key"
                  type={showHcaptchaSecretKey ? "text" : "password"}
                  placeholder="Enter your hCaptcha secret key"
                  value={settings.hcaptchaSecretKey}
                  onChange={(e) => updateSettings('hcaptchaSecretKey', e.target.value)}
                  className="pr-10"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                  onClick={() => setShowHcaptchaSecretKey(!showHcaptchaSecretKey)}
                >
                  {showHcaptchaSecretKey ? (
                    <EyeOff className="h-4 w-4 text-muted-foreground" />
                  ) : (
                    <Eye className="h-4 w-4 text-muted-foreground" />
                  )}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                This key is used for server-side verification of responses.
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ── hCaptcha Widget Mode (Pro only) ── */}
      {hasProvider && settings.provider === 'hcaptcha' && isPro && (
        <Card>
          <CardHeader>
            <CardTitle>Widget Mode</CardTitle>
            <CardDescription>
              Choose how the hCaptcha widget is displayed to users.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <RadioGroup
              value={settings.hcaptchaMode}
              onValueChange={(value) => updateSettings('hcaptchaMode', value as HcaptchaMode)}
              className="space-y-3"
            >
              <div className="flex items-start space-x-3">
                <RadioGroupItem value="visible" id="hcaptcha-visible" className="mt-0.5" />
                <div>
                  <Label htmlFor="hcaptcha-visible" className="font-medium">Visible checkbox</Label>
                  <p className="text-xs text-muted-foreground">
                    Users interact with a visible checkbox widget. Best for transparency.
                  </p>
                </div>
              </div>
              <div className="flex items-start space-x-3">
                <RadioGroupItem value="invisible" id="hcaptcha-invisible" className="mt-0.5" />
                <div>
                  <Label htmlFor="hcaptcha-invisible" className="font-medium">Invisible</Label>
                  <p className="text-xs text-muted-foreground">
                    Runs in the background — only shows a challenge if suspicious activity is detected.
                  </p>
                </div>
              </div>
            </RadioGroup>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
