import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { SettingsGrid } from "@/components/settings-layout"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"
import { cn } from "@/lib/utils"
import { Check, ChevronsUpDown, Loader2, MessageSquare, Link, Shield } from "lucide-react"
import { ContentSettings } from "../../types"

const getApiUrl = () => (window as any).swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
const getNonce = () => (window as any).swiftCommerceData?.restNonce || ''

interface PrivacyPage {
  id: number
  title: string
  url: string
}

interface GeneralTabProps {
  contentSettings: ContentSettings
  updateContentSettings: <K extends keyof ContentSettings>(key: K, value: ContentSettings[K]) => void
}

interface PageComboboxProps {
  pages: PrivacyPage[]
  selectedPageId: number
  loading: boolean
  onSelect: (page: PrivacyPage) => void
}

function PageCombobox({ pages, selectedPageId, loading, onSelect }: PageComboboxProps) {
  const [open, setOpen] = useState(false)
  const selectedPage = pages.find(page => page.id === selectedPageId)

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full justify-between"
          disabled={loading}
        >
          <span className="truncate">
            {loading ? 'Loading pages...' : selectedPage?.title || 'Select a page'}
          </span>
          {loading ? (
            <Loader2 className="ml-2 h-4 w-4 shrink-0 animate-spin opacity-60" />
          ) : (
            <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 pages..." />
          <CommandList>
            <CommandEmpty>No published pages found.</CommandEmpty>
            <CommandGroup>
              {pages.map((page) => (
                <CommandItem
                  key={page.id}
                  value={`${page.title} ${page.url}`}
                  onSelect={() => {
                    onSelect(page)
                    setOpen(false)
                  }}
                >
                  <Check
                    className={cn(
                      "mr-2 h-4 w-4",
                      selectedPageId === page.id ? "opacity-100" : "opacity-0"
                    )}
                  />
                  <span className="truncate">{page.title}</span>
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  )
}

export function GeneralTab({ 
  contentSettings, 
  updateContentSettings
}: GeneralTabProps) {
  const [pages, setPages] = useState<PrivacyPage[]>([])
  const [pagesLoading, setPagesLoading] = useState(false)

  const privacyPolicySource = contentSettings.privacyPolicySource || 'custom'
  const selectedPageUrl = useMemo(() => {
    return pages.find(page => page.id === contentSettings.privacyPolicyPageId)?.url || contentSettings.privacyPolicyUrl
  }, [contentSettings.privacyPolicyPageId, contentSettings.privacyPolicyUrl, pages])

  useEffect(() => {
    if (!contentSettings.showPrivacyLink || privacyPolicySource !== 'page' || pages.length > 0) {
      return
    }

    let isMounted = true

    const fetchPages = async () => {
      setPagesLoading(true)
      try {
        const response = await fetch(`${getApiUrl()}/cookie-consent/pages`, {
          headers: {
            'X-WP-Nonce': getNonce(),
          },
        })

        if (!response.ok) {
          throw new Error('Failed to fetch pages')
        }

        const data = await response.json()
        if (isMounted && data.success && Array.isArray(data.pages)) {
          setPages(data.pages)
        }
      } catch (error) {
        console.error('Error fetching privacy policy pages:', error)
      } finally {
        if (isMounted) {
          setPagesLoading(false)
        }
      }
    }

    fetchPages()

    return () => {
      isMounted = false
    }
  }, [contentSettings.showPrivacyLink, pages.length, privacyPolicySource])

  const updatePrivacyPolicySource = (source: ContentSettings['privacyPolicySource']) => {
    updateContentSettings('privacyPolicySource', source)
  }

  const selectPrivacyPage = (page: PrivacyPage) => {
    updateContentSettings('privacyPolicyPageId', page.id)
    updateContentSettings('privacyPolicyUrl', page.url)
  }

  return (
    <SettingsGrid>
      {/* Popup Content */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5" />
            Popup Content
          </CardTitle>
          <CardDescription>
            Customize the text displayed in your cookie consent popup
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="title">Title</Label>
            <Input
              id="title"
              value={contentSettings.title}
              onChange={(e) => updateContentSettings('title', e.target.value)}
              placeholder="We Value Your Privacy"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="message">Message</Label>
            <Textarea
              id="message"
              value={contentSettings.message}
              onChange={(e) => updateContentSettings('message', e.target.value)}
              placeholder="We use cookies to enhance your browsing experience..."
              rows={3}
            />
            <p className="text-xs text-muted-foreground">
              HTML is supported. Keep it concise and informative.
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Button Text */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Button Text
          </CardTitle>
          <CardDescription>
            Customize the button labels for your consent popup
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-2">
              <Label htmlFor="acceptText">Accept Button</Label>
              <Input
                id="acceptText"
                value={contentSettings.acceptButtonText}
                onChange={(e) => updateContentSettings('acceptButtonText', e.target.value)}
                placeholder="Accept All"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="declineText">Decline Button</Label>
              <Input
                id="declineText"
                value={contentSettings.declineButtonText}
                onChange={(e) => updateContentSettings('declineButtonText', e.target.value)}
                placeholder="Decline"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="settingsText">Settings Button</Label>
              <Input
                id="settingsText"
                value={contentSettings.settingsButtonText}
                onChange={(e) => updateContentSettings('settingsButtonText', e.target.value)}
                placeholder="Cookie Settings"
              />
            </div>
          </div>

          <p className="text-xs text-muted-foreground">
            Accept, decline, and granular settings actions are always shown so visitors can make an equally accessible choice.
          </p>
        </CardContent>
      </Card>

      {/* Privacy Policy Link */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Link className="h-5 w-5" />
            Privacy Policy Link
          </CardTitle>
          <CardDescription>
            Link to your privacy policy page
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center gap-3 mb-4">
            <Switch
              id="showPrivacyLink"
              checked={contentSettings.showPrivacyLink}
              onCheckedChange={(checked) => updateContentSettings('showPrivacyLink', checked)}
            />
            <Label htmlFor="showPrivacyLink" className="cursor-pointer">
              Show Privacy Policy Link
            </Label>
          </div>

          {contentSettings.showPrivacyLink && (
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="privacyText">Link Text</Label>
                <Input
                  id="privacyText"
                  value={contentSettings.privacyPolicyText}
                  onChange={(e) => updateContentSettings('privacyPolicyText', e.target.value)}
                  placeholder="Privacy Policy"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="privacySource">Link Source</Label>
                <Select
                  value={privacyPolicySource}
                  onValueChange={(value) => updatePrivacyPolicySource(value as ContentSettings['privacyPolicySource'])}
                >
                  <SelectTrigger id="privacySource">
                    <SelectValue placeholder="Choose source" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="page">Existing Page</SelectItem>
                    <SelectItem value="custom">Custom URL</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {privacyPolicySource === 'page' ? (
                <div className="space-y-2 md:col-span-2">
                  <Label>Privacy Policy Page</Label>
                  <PageCombobox
                    pages={pages}
                    selectedPageId={contentSettings.privacyPolicyPageId || 0}
                    loading={pagesLoading}
                    onSelect={selectPrivacyPage}
                  />
                  {selectedPageUrl && (
                    <p className="text-xs text-muted-foreground truncate">
                      {selectedPageUrl}
                    </p>
                  )}
                </div>
              ) : (
                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="privacyUrl">Custom URL</Label>
                  <Input
                    id="privacyUrl"
                    value={contentSettings.privacyPolicyUrl}
                    onChange={(e) => updateContentSettings('privacyPolicyUrl', e.target.value)}
                    placeholder="/privacy-policy"
                  />
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>
    </SettingsGrid>
  )
}
