import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Loader2, Search, CheckCircle2, Globe, FileText, Archive, AlertCircle, X } from 'lucide-react';
import { toast } from '@/components/ui/toast';
import { __, sprintf } from '@wordpress/i18n';
import { apiGateway } from '../api/gateway.js';

const WidgetControl = () => {
  const [pages, setPages] = useState([]);
  const [settings, setSettings] = useState({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [isWidgetControlEnabled, setIsWidgetControlEnabled] = useState(false);
  const [showSearchResults, setShowSearchResults] = useState(false);
  const searchRef = useRef(null);

  // Load pages and settings
  const loadPagesSettings = async () => {
    try {
      setLoading(true);
      const response = await apiGateway.get('page-settings');

      if (response.success) {
        setPages(response.pages || []);
        setSettings(response.settings || {});

        // Load widget control toggle state from API response (backend uses get_option)
        setIsWidgetControlEnabled(response.widget_control_enabled === true);
      }
    } catch (error) {
      toast.error(__('Failed to load page settings', 'surefeedback-cloud'));
      // Default to false (widget shows everywhere) when API fails - safest default
      setIsWidgetControlEnabled(false);
    } finally {
      setLoading(false);
    }
  };

  // Handle widget control toggle change
  const handleWidgetControlToggle = async (enabled) => {
    const previousState = isWidgetControlEnabled;
    setIsWidgetControlEnabled(enabled);

    // If disabling Widget Control, clear all page settings (widget shows everywhere)
    if (!enabled) {
      setSettings({});
      setHasUnsavedChanges(true);
    }

    // Save to backend using update_option via REST API
    try {
      const response = await apiGateway.post('page-settings/widget-control', {
        widget_control_enabled: enabled,
      });

      if (!response.success) {
        throw new Error(response.message || 'Failed to save widget control state');
      }
    } catch (error) {
      // Revert to previous state on error
      setIsWidgetControlEnabled(previousState);
      if (previousState) {
        // Reload settings to restore previous page settings if we reverted
        await loadPagesSettings();
      }
      toast.error(__('Failed to save widget control setting', 'surefeedback-cloud'));
    }
  };

  useEffect(() => {
    loadPagesSettings();
  }, []);

  // Handle clicking outside search results
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (searchRef.current && !searchRef.current.contains(event.target)) {
        setShowSearchResults(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Add page to enabled list
  const handleAddPage = (page) => {
    setSettings((prev) => ({
      ...prev,
      [page.id]: true,
    }));
    setHasUnsavedChanges(true);
    setSearchTerm('');
    setShowSearchResults(false);
    toast.success(sprintf(__('Added %s to enabled pages', 'surefeedback-cloud'), page.title));
  };

  // Remove page from enabled list
  const handleRemovePage = (pageId) => {
    setSettings((prev) => {
      const newSettings = { ...prev };
      delete newSettings[pageId];
      return newSettings;
    });
    setHasUnsavedChanges(true);

    const page = pages.find(p => p.id === pageId);
    if (page) {
      toast.success(sprintf(__('Removed %s from enabled pages', 'surefeedback-cloud'), page.title));
    }
  };

  // Save settings
  const saveSettings = async () => {
    try {
      setSaving(true);
      const response = await apiGateway.post('page-settings', {
        settings: settings,
      });

      if (response.success) {
        toast.success(__('Page settings saved successfully', 'surefeedback-cloud'));
        setHasUnsavedChanges(false);
        await loadPagesSettings();
      }
    } catch (error) {
      toast.error(__('Failed to save settings', 'surefeedback-cloud'));
    } finally {
      setSaving(false);
    }
  };

  // Get page icon based on type
  const getPageIcon = (type) => {
    switch (type) {
      case 'home':
      case 'blog':
        return <Globe className="h-4 w-4" />;
      case 'page':
      case 'post':
        return <FileText className="h-4 w-4" />;
      case 'archive':
      case 'search':
      case '404':
        return <Archive className="h-4 w-4" />;
      default:
        return <FileText className="h-4 w-4" />;
    }
  };

  // Get page type badge
  const getPageTypeBadge = (type, typeLabel) => {
    return (
      <Badge className="bg-[#F9FAFB] text-[#374151] border-[0.5px] border-[#E5E7EB] rounded-full shadow-none px-2.5 py-0.5 text-xs font-medium hover:bg-gray-100">
        {typeLabel || type}
      </Badge>
    );
  };

  // Filter search results - only show pages not already in enabled list
  const searchResults = pages.filter((page) => {
    const matchesSearch = page.title.toLowerCase().includes(searchTerm.toLowerCase());
    const notAlreadyEnabled = !settings[page.id];
    return matchesSearch && notAlreadyEnabled;
  });

  // Get enabled pages for display
  const enabledPages = pages.filter((page) => settings[page.id] === true);

  if (loading) {
    return (
      <div className="flex justify-center items-start bg-background p-4 pt-8">
        <Card className="shadow-sm w-full rounded-lg border border-border max-w-4xl">
          <CardContent className="flex flex-col space-y-6 py-8 w-full">
            <div className="space-y-4 sm:space-y-6">
              {/* Header Skeleton */}
              <div>
                <Skeleton className="h-7 w-40 mb-2" />
                <Skeleton className="h-4 w-80" />
              </div>

              {/* Search Bar Skeleton */}
              <Card className="w-full rounded-lg border border-border shadow-none">
                <CardHeader className="p-4 sm:p-6 !pb-0">
                  <Skeleton className="h-6 w-32 mb-2" />
                  <Skeleton className="h-4 w-64" />
                </CardHeader>
                <CardContent className="px-6 !pt-4">
                  <Skeleton className="h-10 w-full mb-4" />

                  {/* Enabled Pages List Skeleton */}
                  <div className="space-y-2 mb-4">
                    {[1, 2, 3].map((i) => (
                      <div key={i} className="flex items-center gap-3 p-4 border-[0.5px] border-[#E5E7EB] rounded-lg">
                        <div className="flex-1 min-w-0 space-y-2">
                          <Skeleton className="h-5 w-48" />
                          <Skeleton className="h-4 w-full" />
                        </div>
                        <Skeleton className="h-8 w-8 rounded" />
                      </div>
                    ))}
                  </div>

                  {/* Save Actions Bar Skeleton */}
                  <div className="border-t pt-4 mt-4 bg-gray-50 -mx-6 px-6 -mb-6 pb-6 rounded-b-lg">
                    <div className="flex items-center justify-between">
                      <Skeleton className="h-6 w-32" />
                      <div className="flex gap-3">
                        <Skeleton className="h-9 w-24" />
                        <Skeleton className="h-9 w-32" />
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex justify-center items-start bg-background p-4 pt-8">
      <Card className="shadow-sm w-full rounded-lg border border-border max-w-4xl">
        <CardContent className="flex flex-col space-y-6 py-8 w-full">
          <div className="space-y-4 sm:space-y-6">
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div className="flex-1">
                <h2 className="text-xl font-semibold text-foreground">{__('Enable the Commenting Widget on Selected Pages', 'surefeedback-cloud')}</h2>
                <p className="text-sm text-muted-foreground mt-1">
                  {isWidgetControlEnabled
                    ? __('Widget is hidden on all pages. Search and select pages below to enable the widget on specific pages.', 'surefeedback-cloud')
                    : __('Widget is displayed on all pages. Enable this option to restrict the widget to specific pages only.', 'surefeedback-cloud')
                  }
                </p>
              </div>
              <div className="flex items-center gap-3">
                <label htmlFor="widget-control-toggle" className="text-sm font-medium text-foreground">
                  {isWidgetControlEnabled ? __('Yes', 'surefeedback-cloud') : __('No', 'surefeedback-cloud')}
                </label>
                <Switch
                  id="widget-control-toggle"
                  checked={isWidgetControlEnabled}
                  onCheckedChange={handleWidgetControlToggle}
                />
              </div>
            </div>

            {/* Search and Enabled Pages List */}
            {isWidgetControlEnabled && (
              <Card className="w-full rounded-lg border border-border shadow-none">
                <CardHeader className="p-4 sm:p-6 !pb-0">
                  <CardTitle className="text-base sm:text-lg">{__('Select Pages', 'surefeedback-cloud')}</CardTitle>
                  <CardDescription className="text-xs sm:text-sm mt-1">
                    {__('Search for pages and click to enable the widget. Only selected pages will display the widget.', 'surefeedback-cloud')}
                  </CardDescription>
                </CardHeader>
                <CardContent className="px-6 !pt-4">
                  {/* Search Bar */}
                  <div className="relative mb-4" ref={searchRef}>
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder={__('Search pages to enable...', 'surefeedback-cloud')}
                        value={searchTerm}
                        onChange={(e) => {
                          setSearchTerm(e.target.value);
                          setShowSearchResults(e.target.value.length > 0);
                        }}
                        onFocus={() => {
                          if (searchTerm.length > 0) {
                            setShowSearchResults(true);
                          }
                        }}
                        className="pl-10 text-sm h-10"
                      />
                    </div>

                    {/* Search Results Dropdown */}
                    {showSearchResults && searchTerm && (
                      <div className="absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-64 overflow-y-auto">
                        {searchResults.length === 0 ? (
                          <div className="p-4 text-center text-sm text-muted-foreground">
                            <AlertCircle className="h-5 w-5 mx-auto mb-2" />
                            <p>{__('No pages found or all matching pages are already enabled', 'surefeedback-cloud')}</p>
                          </div>
                        ) : (
                          <div className="py-1">
                            {searchResults.map((page) => (
                              <button
                                key={page.id}
                                onClick={() => handleAddPage(page)}
                                className="w-full text-left px-4 py-3 hover:bg-gray-50 transition-colors duration-150 border-b border-gray-100 last:border-b-0"
                              >
                                <div className="flex items-center gap-3">
                                  <div className="flex-shrink-0 text-muted-foreground">
                                    {getPageIcon(page.type)}
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <div className="font-medium text-gray-900 truncate text-sm">
                                      {page.title}
                                    </div>
                                    {page.url && (
                                      <div className="text-xs text-[#6B7280] truncate mt-0.5">
                                        {page.url}
                                      </div>
                                    )}
                                  </div>
                                  <div className="flex-shrink-0">
                                    {getPageTypeBadge(page.type, page.type_label)}
                                  </div>
                                </div>
                              </button>
                            ))}
                          </div>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Enabled Pages List */}
                  <div className="space-y-2 mb-4">
                    {enabledPages.length === 0 ? (
                      <div className="text-center py-8 px-4 border-2 border-dashed border-gray-200 rounded-lg">
                        <AlertCircle className="h-8 w-8 mx-auto mb-2 text-muted-foreground" />
                        <p className="text-sm text-muted-foreground font-medium mb-1">
                          {__('No pages selected', 'surefeedback-cloud')}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {__('Widget is currently hidden on all pages. Search and select pages above to enable the widget.', 'surefeedback-cloud')}
                        </p>
                      </div>
                    ) : (
                      <>
                        <div className="text-sm font-medium text-gray-700 mb-2">
                          {sprintf(__('Enabled Pages (%d)', 'surefeedback-cloud'), enabledPages.length)}
                        </div>
                        {enabledPages.map((page) => (
                          <div
                            key={page.id}
                            className="flex items-center gap-3 p-4 border-[0.5px] border-[#E5E7EB] rounded-lg transition-colors duration-150 hover:border-gray-300"
                          >
                            <div className="flex-shrink-0 text-muted-foreground">
                              {getPageIcon(page.type)}
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="font-sm text-gray-900 truncate text-sm">
                                {page.title}
                              </div>
                              {page.url && (
                                <div className="text-xs text-[#6B7280] truncate mt-0.5">
                                  {page.url}
                                </div>
                              )}
                            </div>
                            <div className="flex items-center gap-2">
                              <div className="flex-shrink-0">
                                {getPageTypeBadge(page.type, page.type_label)}
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleRemovePage(page.id)}
                                className="h-8 w-8 p-0 hover:bg-red-50 hover:text-red-600"
                              >
                                <X className="h-4 w-4" />
                              </Button>
                            </div>
                          </div>
                        ))}
                      </>
                    )}
                  </div>

                  {/* Save Actions Bar */}
                  <div className="border-t pt-4 mt-4 bg-gray-50 -mx-6 px-6 -mb-6 pb-6 rounded-b-lg">
                    <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
                      <div className="flex items-center gap-2">
                        {hasUnsavedChanges && (
                          <div className="flex items-center gap-2 text-xs sm:text-sm text-orange-600 bg-orange-50 px-3 py-2 rounded-md border border-orange-200">
                            <AlertCircle className="h-4 w-4 flex-shrink-0" />
                            <span className="font-medium">{__('Unsaved changes', 'surefeedback-cloud')}</span>
                          </div>
                        )}
                        {!hasUnsavedChanges && (
                          <div className="flex items-center gap-2 text-xs sm:text-sm text-gray-600">
                            <CheckCircle2 className="h-4 w-4 text-green-600 flex-shrink-0" />
                            <span>{__('All changes saved', 'surefeedback-cloud')}</span>
                          </div>
                        )}
                      </div>
                      <div className="flex gap-3">
                        <Button
                          variant="outline"
                          onClick={loadPagesSettings}
                          disabled={saving || !hasUnsavedChanges}
                          className="flex-1 sm:flex-initial sm:min-w-[100px] text-sm h-9"
                        >
                          {__('Cancel', 'surefeedback-cloud')}
                        </Button>
                        <Button
                          onClick={saveSettings}
                          disabled={saving || !hasUnsavedChanges}
                          className="flex-1 sm:flex-initial sm:min-w-[140px] text-sm h-9"
                        >
                          {saving ? (
                            <>
                              <Loader2 className="h-4 w-4 animate-spin" />
                              <span>{__('Saving...', 'surefeedback-cloud')}</span>
                            </>
                          ) : (
                            <span>{__('Save Changes', 'surefeedback-cloud')}</span>
                          )}
                        </Button>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default WidgetControl;
