import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"
import { Check, ChevronsUpDown, X } from "lucide-react"
import { cn } from "@/lib/utils"
import { usePro } from "@/contexts/pro-context"
import { ProIndicator } from "@/components/pro/pro-indicator"
import {
  RecaptchaState,
  RecaptchaLocation,
  recaptchaLocations,
  recaptchaThemes,
  recaptchaSizes,
  RecaptchaTheme,
  RecaptchaSize,
  captchaRoleOptions,
} from "../../config"

interface SettingsTabProps {
  settings: RecaptchaState
  toggleLocation: (locationId: RecaptchaLocation) => void
  toggleBypassRole: (role: string) => void
  updateSettings: <K extends keyof RecaptchaState>(key: K, value: RecaptchaState[K]) => void
}

export function SettingsTab({ settings, toggleLocation, toggleBypassRole, updateSettings }: SettingsTabProps) {
  const { isPro } = usePro()
  const [roleSelectOpen, setRoleSelectOpen] = useState(false)

  // Roles not yet selected (shown in the combobox dropdown)
  const selectedRoles = captchaRoleOptions.filter((role) => settings.bypassRoles.includes(role.value))

  // Free locations are always shown
  const freeLocations = recaptchaLocations.filter(loc => !loc.isPro)
  // Pro locations only shown to Pro users
  const proLocations = recaptchaLocations.filter(loc => loc.isPro)

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* Left Column - Protected Pages */}
      <div className="space-y-6">
        {/* Protected Pages - Free Locations */}
        <Card>
          <CardHeader>
            <CardTitle>Protected Pages</CardTitle>
            <CardDescription>
              Select which pages should be protected by reCAPTCHA
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid gap-3">
              {freeLocations.map((location) => {
                const locationKey = location.id as RecaptchaLocation
                const isChecked = settings.locations[locationKey] || false
                
                return (
                  <div
                    key={location.id}
                    className={`
                      relative flex items-start gap-3 rounded-lg border p-3 cursor-pointer transition-colors
                      ${isChecked ? 'border-primary bg-primary/5' : 'border-muted hover:border-muted-foreground/50'}
                    `}
                    onClick={() => toggleLocation(locationKey)}
                  >
                    <Checkbox
                      id={location.id}
                      checked={isChecked}
                      onCheckedChange={() => toggleLocation(locationKey)}
                      className="mt-0.5"
                    />
                    <div className="flex-1 space-y-0.5">
                      <div className="flex items-center gap-2">
                        <Label 
                          htmlFor={location.id} 
                          className="font-medium cursor-pointer text-sm"
                        >
                          {location.name}
                        </Label>
                        {location.requiresWooCommerce && (
                          <Badge variant="outline" className="text-xs">
                            WooCommerce
                          </Badge>
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {location.description}
                      </p>
                    </div>
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>

        {/* Pro Locations — hidden entirely for Free users */}
        {isPro && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                Additional Locations
                <ProIndicator size="sm" />
              </CardTitle>
              <CardDescription>
                Protect more forms with reCAPTCHA
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3">
                {proLocations.map((location) => {
                  const locationKey = location.id as RecaptchaLocation
                  const isChecked = settings.locations[locationKey] || false
                  
                  return (
                    <div
                      key={location.id}
                      className={`
                        relative flex items-start gap-3 rounded-lg border p-3 cursor-pointer transition-colors
                        ${isChecked ? 'border-primary bg-primary/5' : 'border-muted hover:border-muted-foreground/50'}
                      `}
                      onClick={() => toggleLocation(locationKey)}
                    >
                      <Checkbox
                        id={location.id}
                        checked={isChecked}
                        onCheckedChange={() => toggleLocation(locationKey)}
                        className="mt-0.5"
                      />
                      <div className="flex-1 space-y-0.5">
                        <div className="flex items-center gap-2">
                          <Label 
                            htmlFor={location.id} 
                            className="font-medium cursor-pointer text-sm"
                          >
                            {location.name}
                          </Label>
                          {location.requiresWooCommerce && (
                            <Badge variant="outline" className="text-xs">
                              WooCommerce
                            </Badge>
                          )}
                        </div>
                        <p className="text-xs text-muted-foreground">
                          {location.description}
                        </p>
                      </div>
                    </div>
                  )
                })}
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* Right Column — Pro-only sections hidden entirely for Free users */}
      {isPro && (
        <div className="space-y-6">
          {/* Appearance Settings */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                Appearance
                <ProIndicator size="sm" />
              </CardTitle>
              <CardDescription>
                Customize the look of your reCAPTCHA widget
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-6">
                {/* Theme Selection — vertical radio group */}
                <div className="space-y-3">
                  <Label className="text-sm font-medium">Theme</Label>
                  <RadioGroup
                    value={settings.theme}
                    onValueChange={(value) => updateSettings('theme', value as RecaptchaTheme)}
                    className="gap-3"
                  >
                    {recaptchaThemes.map((theme) => (
                      <div key={theme.id} className="flex items-center gap-2.5">
                        <RadioGroupItem value={theme.id} id={`theme-${theme.id}`} />
                        <Label htmlFor={`theme-${theme.id}`} className="text-sm font-normal cursor-pointer">
                          {theme.name}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>

                {/* Size Selection — vertical radio group */}
                <div className="space-y-3">
                  <Label className="text-sm font-medium">Size</Label>
                  <RadioGroup
                    value={settings.size}
                    onValueChange={(value) => updateSettings('size', value as RecaptchaSize)}
                    className="gap-3"
                  >
                    {recaptchaSizes.map((size) => (
                      <div key={size.id} className="flex items-center gap-2.5">
                        <RadioGroupItem value={size.id} id={`size-${size.id}`} />
                        <Label htmlFor={`size-${size.id}`} className="text-sm font-normal cursor-pointer">
                          {size.name}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* IP Whitelist */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                IP Whitelist
                <ProIndicator size="sm" />
              </CardTitle>
              <CardDescription>
                Disable reCAPTCHA for specific IP addresses or ranges
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-2">
                <Label htmlFor="ipWhitelist">IP Addresses / Ranges</Label>
                <Textarea
                  id="ipWhitelist"
                  placeholder={"Enter IP addresses (one per line)\nExamples:\n192.168.1.1\n10.0.0.0/24"}
                  value={settings.ipWhitelist}
                  onChange={(e) => updateSettings('ipWhitelist', e.target.value)}
                  className="min-h-[100px] font-mono text-sm"
                />
                <p className="text-xs text-muted-foreground">
                  Enter one IP address or range per line. Supports CIDR notation.
                </p>
              </div>
            </CardContent>
          </Card>

          {/* Role Bypass */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                Role Bypass
                <ProIndicator size="sm" />
              </CardTitle>
              <CardDescription>
                Skip CAPTCHA verification for logged-in users with specific roles
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              <Popover open={roleSelectOpen} onOpenChange={setRoleSelectOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={roleSelectOpen}
                    className="w-full justify-between font-normal"
                  >
                    <span className="text-muted-foreground">
                      {selectedRoles.length > 0
                        ? `${selectedRoles.length} role${selectedRoles.length === 1 ? '' : 's'} selected`
                        : 'Select roles to bypass…'}
                    </span>
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
                  <Command>
                    <CommandInput placeholder="Search roles…" />
                    <CommandList>
                      <CommandEmpty>No role found.</CommandEmpty>
                      <CommandGroup>
                        {captchaRoleOptions.map((role) => {
                          const isChecked = settings.bypassRoles.includes(role.value)
                          return (
                            <CommandItem
                              key={role.value}
                              value={role.label}
                              onSelect={() => toggleBypassRole(role.value)}
                            >
                              <Check
                                className={cn(
                                  "mr-2 h-4 w-4",
                                  isChecked ? "opacity-100" : "opacity-0"
                                )}
                              />
                              {role.label}
                            </CommandItem>
                          )
                        })}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>

              {selectedRoles.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {selectedRoles.map((role) => (
                    <Badge
                      key={role.value}
                      variant="secondary"
                      className="gap-1 pr-1 font-normal"
                    >
                      {role.label}
                      <button
                        type="button"
                        onClick={() => toggleBypassRole(role.value)}
                        className="rounded-sm opacity-60 hover:opacity-100 hover:bg-muted-foreground/20 transition-opacity"
                        aria-label={`Remove ${role.label}`}
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}

              <p className="text-xs text-muted-foreground">
                Selected roles will not see CAPTCHA challenges when logged in.
              </p>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}
