import React, { useState, useMemo } from 'react';
import type { DashboardData } from './types';
import {
  Smartphone,
  Globe,
  CheckCircle2,
  Info,
  Plus,
  Trash2,
  GripVertical,
  Search,
  X,
  ChevronRight,
  ChevronDown,
  Lock,
  Flag,
  List,
  AlignLeft,
  Hash,
  ShieldCheck
} from 'lucide-react';
import { Switch } from './components/ui/switch';
import { getTimezone } from 'countries-and-timezones';
import { SearchableSelect } from './components/ui/searchable-select';

import {
  SettingCard,
  FlatTabs,
  ModernCardHeader,
  StatusMessage,
  SettingInput,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SecondaryButton,
  MethodButton,
  SaveWithStatus
} from './components/ui/settings-ui';
import { CompactSettingCard } from './components/ui/CompactSettingCard';
import { useSettingsSave } from './hooks/useSettingsSave';

interface PhoneField {
  id: string;
  name: string;
  enabled: string;
}

interface Country {
  iso2: string;
  name: string;
  dialCode: string;
  region: string;
}

interface PhoneFieldSettingsData {
  settings: {
    default_country_code: string;
    enable_ip_detection: boolean;
    enable_carrier_lookup: boolean;
    enable_whatsapp_check: boolean;
    country_code_alignment: 'auto' | 'left' | 'right';
    phone_fields: PhoneField[];
    enabled_countries: string[];
  };
  allCountries: Country[];
  userIp: string;
  i18n: {
    [key: string]: string;
  };
  ajaxUrl: string;
  nonce: string;
}

const PhoneFieldSettings: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = rootData?.phoneFieldData as PhoneFieldSettingsData;

  const [activeTab, setActiveTab] = useState('general');
  const [settings, setSettings] = useState(data?.settings);
  const [searchQuery, setSearchQuery] = useState('');
  const [collapsedRegions, setCollapsedRegions] = useState<string[]>([]);

  // Adjust state during render if props change
  const [prevData, setPrevData] = useState(data);
  if (data && data !== prevData) {
    setPrevData(data);
    if (data.settings) {
      setSettings(data.settings);
    }
  }


  const t = useMemo(() => ({
    ...(data?.i18n || {}),
    title: "Advanced Country Code",
    subtitle: "The advanced country code feature allows you to automatically correct your customer numbers according to their country code so that your website can send messages correctly."
  } as { [key: string]: string }), [data?.i18n]);

  // Group countries by region
  const countriesByRegion = useMemo(() => {
    const grouped: { [region: string]: Country[] } = {};
    (data?.allCountries || []).forEach(country => {
      const region = country.region || 'Other';
      if (!grouped[region]) grouped[region] = [];
      grouped[region].push(country);
    });
    return grouped;
  }, [data?.allCountries]);

  const sortedRegions = useMemo(() => Object.keys(countriesByRegion).sort(), [countriesByRegion]);

  const defaultCountry = useMemo(() => {
    return (data?.allCountries || []).find(c => c.iso2 === settings?.default_country_code) || (data?.allCountries || [])[0];
  }, [settings?.default_country_code, data?.allCountries]);

  const activeCountriesCount = settings?.enabled_countries?.length || 0;
  const totalCountriesCount = (data?.allCountries || []).length || 0;
  const inactiveCountriesCount = totalCountriesCount - activeCountriesCount;

  const { saveStatus, hasUnsavedChanges, isSaving, handleSave, markDirty } = useSettingsSave({
    onSave: async () => {
      const globalData = rootData.global;
      const restUrl = globalData?.settingsRestUrl || '';
      const wpNonce = globalData?.wpRestNonce || '';

      if (!restUrl) return false;

      try {
        const response = await fetch(restUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': wpNonce
          },
          body: JSON.stringify({
            settings: {
              wawp_intl_tel_options: settings
            }
          }),
        });

        if (response.ok) {
          if (settings?.default_country_code && window.wawpDashboardData?.global) {
            window.wawpDashboardData.global.country = settings.default_country_code.toUpperCase();
          }
          window.dispatchEvent(new CustomEvent('wawp-refresh-data'));
          return true;
        }
        return false;
      } catch (error) {
        console.error('Phone settings save error:', error);
        return false;
      }
    }
  });

  // Before unload warning
  React.useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges]);

  const updateSetting = <K extends keyof PhoneFieldSettingsData['settings']>(key: K, value: PhoneFieldSettingsData['settings'][K]) => {
    setSettings(prev => prev ? ({ ...prev, [key]: value }) : prev);
    markDirty();
  };

  // Internal Geolocation Bypass
  const [hasGeoIpAttempted, setHasGeoIpAttempted] = useState(false);
  if (settings?.enable_ip_detection && !settings?.default_country_code && !hasGeoIpAttempted) {
    setHasGeoIpAttempted(true);
    try {
      const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
      const timezoneInfo = getTimezone(tz);
      const countryCode = timezoneInfo?.countries[0];
      if (countryCode && data?.allCountries?.find(c => c.iso2 === countryCode)) {
        // We can update state during render for the same component
        setSettings(prev => prev ? ({ ...prev, default_country_code: countryCode }) : prev);
        markDirty();
      }
    } catch (e: unknown) {
      console.error('Bypass GeoIP Error:', e);
    }
  }

  if (!data || !settings) return null;


  const iso2ToFlag = (iso: string) => {
    if (!iso) return '';
    return Array.from(iso.toUpperCase())
      .map(char => String.fromCodePoint(char.charCodeAt(0) + 127397))
      .join('');
  };

  const toggleCountry = (iso2: string) => {
    let newEnabled = [...settings.enabled_countries];
    if (newEnabled.includes(iso2)) {
      newEnabled = newEnabled.filter(i => i !== iso2);
    } else {
      newEnabled.push(iso2);
    }
    updateSetting('enabled_countries', newEnabled);
  };

  const selectAll = () => {
    updateSetting('enabled_countries', data.allCountries.map(c => c.iso2));
  };

  const deselectAll = () => {
    updateSetting('enabled_countries', []);
  };

  const toggleRegion = (region: string) => {
    if (collapsedRegions.includes(region)) {
      setCollapsedRegions(collapsedRegions.filter(r => r !== region));
    } else {
      setCollapsedRegions([...collapsedRegions, region]);
    }
  };

  const addPhoneField = () => {
    const newFields = [
      ...settings.phone_fields,
      { id: '', name: '', enabled: '1' }
    ];
    updateSetting('phone_fields', newFields);
  };

  const removePhoneField = (index: number) => {
    const newFields = settings.phone_fields.filter((_, i) => i !== index);
    updateSetting('phone_fields', newFields);
  };

  const updatePhoneField = (index: number, key: keyof PhoneField, value: string) => {
    const newFields = [...settings.phone_fields];
    newFields[index] = { ...newFields[index], [key]: value };
    setSettings({ ...settings, phone_fields: newFields });
    markDirty();
  };

  const coreSelectors = ['#billing-phone', '#billing_phone', '#wawp_phone', '#billing_phone_popup'];

  const tabs = [
    { id: 'general', label: t.general, icon: Smartphone },
    { id: 'integrations', label: t.integrations, icon: Info },
    { id: 'allowed_countries', label: t.allowedCountries, icon: Globe },
  ];

  return (
    <SettingsLayout>
      <SettingsHeader
        title={t.title}
        description={t.subtitle}
      >
        <SaveWithStatus
          saveStatus={saveStatus}
          hasUnsavedChanges={hasUnsavedChanges}
          isSaving={isSaving}
          onSave={() => handleSave(false)}
        />
      </SettingsHeader>

      <FlatTabs
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />

      <div className="space-y-6">
        {activeTab === 'general' && (
          <div className="space-y-6 animate-in slide-in-from-bottom-2 duration-300">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.defaultCountry}
                description={t.defaultCountryDesc}
                icon={Flag}
              />

              <div className="p-6 md:p-8 space-y-6">
                <SearchableSelect
                  options={data.allCountries
                    .filter(c => settings.enabled_countries.includes(c.iso2))
                    .map(country => ({
                      value: country.iso2,
                      label: `${iso2ToFlag(country.iso2)} ${country.name} (+${country.dialCode})`
                    }))}
                  value={settings.default_country_code}
                  onChange={(val) => updateSetting('default_country_code', val)}
                  placeholder={t.selectCountry || "Select Country"}
                  searchPlaceholder={t.searchCountries || "Search countries..."}
                  className="h-12 bg-slate-50/50 border-slate-200 text-slate-700 font-bold text-[13px] hover:bg-white hover:border-[#004449]/30 transition-all rounded-[5px]"
                />

                <StatusMessage
                  type="active"
                  message={`${t.example}: ${defaultCountry.name} (+${defaultCountry.dialCode})`}
                  className="mt-2"
                />
              </div>
            </SettingCard>

            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.alignment}
                description={t.alignmentDesc}
                icon={AlignLeft}
                rightAction={
                  <div className="hidden sm:flex items-center gap-2 px-3 py-1 bg-slate-50 border border-slate-100 rounded-lg text-[9px] font-bold text-slate-400 uppercase tracking-widest">
                    <Info className="w-3.5 h-3.5" />
                    {t.alignmentRecommended}
                  </div>
                }
              />

              <div className="p-3 md:p-5 grid grid-cols-1 md:grid-cols-3 gap-3">
                {[
                  { id: 'auto', label: t.alignmentAuto, desc: 'Auto-detect by language' },
                  { id: 'left', label: t.alignmentLeft, desc: 'Force LTR alignment' },
                  { id: 'right', label: t.alignmentRight, desc: 'Force RTL alignment' },
                ].map((option) => (
                  <MethodButton
                    key={option.id}
                    active={settings.country_code_alignment === option.id}
                    onClick={() => updateSetting('country_code_alignment', option.id as 'auto' | 'left' | 'right')}
                    label={option.label}
                    description={option.desc}
                    icon={option.id === 'auto' ? Smartphone : (option.id === 'left' ? AlignLeft : List)}
                  />
                ))}
              </div>
            </SettingCard>

            <CompactSettingCard
              title={t.enableCarrierTitle}
              description={t.enableCarrierDesc}
              icon={Search}
              checked={settings.enable_carrier_lookup}
              onChange={(checked: boolean) => updateSetting('enable_carrier_lookup', checked)}
              statusMessage={settings.enable_carrier_lookup ? t.carrierLookupActive : t.ipDetectInactive}
              statusType={settings.enable_carrier_lookup ? 'active' : 'inactive'}
            />
          </div>
        )}

        {activeTab === 'integrations' && (
          <div className="space-y-6 animate-in slide-in-from-bottom-2 duration-300 pb-20">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.targetFields}
                description={t.targetFieldsDesc}
                icon={List}
              />

              <div className="p-3 md:p-5">
                <StatusMessage
                  type="active"
                  message={t.targetFieldsStatus}
                  className="mb-5"
                />

                <div className="space-y-4">
                  {settings.phone_fields.map((field, index) => (
                    <div key={index} className="flex flex-col lg:flex-row items-end lg:items-center gap-6 p-3 border border-slate-100 rounded-[4px] bg-slate-50/30 hover:bg-white hover:border-slate-200 transition-all group">
                      <div className="hidden lg:block text-slate-300">
                        <GripVertical className="w-5 h-5 cursor-grab" />
                      </div>

                      <div className="w-full grid grid-cols-1 md:grid-cols-2 gap-3">
                        <SettingInput
                          label={t.cssSelector}
                          value={field.id}
                          onChange={(val: string) => updatePhoneField(index, 'id', val)}
                          placeholder=""
                          icon={Hash}
                          className={coreSelectors.includes(field.id) ? "opacity-70 pointer-events-none" : ""}
                        />
                        <SettingInput
                          label={t.internalName}
                          value={field.name}
                          onChange={(val: string) => updatePhoneField(index, 'name', val)}
                          placeholder=""
                          icon={AlignLeft}
                        />
                      </div>

                      <div className="flex flex-col items-center gap-1.5 w-full lg:w-auto mt-2 lg:mt-0">
                        <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Active</span>
                        <div className="flex items-center gap-3">
                          <Switch
                            checked={field.enabled === '1'}
                            onCheckedChange={(checked) => {
                              const newFields = [...settings.phone_fields];
                              newFields[index] = { ...newFields[index], enabled: checked ? '1' : '0' };
                              updateSetting('phone_fields', newFields);
                            }}
                          />

                          {coreSelectors.includes(field.id) ? (
                            <div className="p-1.5 bg-slate-100 rounded-[4px] text-slate-300 border border-slate-200" title={t.coreFieldNote}>
                              <Lock className="w-4 h-4" />
                            </div>
                          ) : (
                            <button
                              onClick={() => removePhoneField(index)}
                              className="p-2 text-slate-300 hover:text-red-500 hover:bg-red-50 rounded-[4px] transition-all"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}

                  <div className="flex justify-center pt-6">
                    <AdminButton
                      onClick={addPhoneField}
                      icon={Plus}
                    >
                      {t.addNewField}
                    </AdminButton>
                  </div>
                </div>
              </div>
            </SettingCard>
          </div>
        )}

        {activeTab === 'allowed_countries' && (
          <div className="space-y-6 animate-in slide-in-from-bottom-2 duration-300 pb-20">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.allowedCountriesTitle}
                description={t.allowedCountriesDesc}
                icon={Globe}
                rightAction={
                  <div className="flex gap-2">
                    <span className="px-3 py-1 bg-emerald-50 text-emerald-700 text-[10px] font-bold rounded-lg uppercase tracking-widest border border-emerald-100/50">
                      {activeCountriesCount} {t.active}
                    </span>
                    <span className="px-3 py-1 bg-red-50 text-red-700 text-[10px] font-bold rounded-lg uppercase tracking-widest border border-red-100/50">
                      {inactiveCountriesCount} {t.inactive}
                    </span>
                  </div>
                }
              />

              <div className="p-3">
                <div className="flex flex-col sm:flex-row items-stretch gap-3 mb-5">
                  <div className="flex-1 w-full">
                    <SettingInput
                      label={t.searchCountries}
                      value={searchQuery}
                      onChange={(val: string) => setSearchQuery(val)}
                      placeholder="Live search by country name or dial code..."
                      icon={Search}
                      labelHidden
                      className="w-full !h-10"
                    />
                  </div>
                  <div className="flex gap-2 items-center pt-1">
                    <SecondaryButton
                      onClick={selectAll}
                      icon={CheckCircle2}
                      size="lg"
                    >
                      {t.selectAll}
                    </SecondaryButton>
                    <SecondaryButton
                      onClick={deselectAll}
                      icon={X}
                      size="lg"
                    >
                      {t.deselectAll}
                    </SecondaryButton>
                  </div>
                </div>

                <div className="space-y-4 max-h-[700px] overflow-y-auto pr-2 custom-scrollbar no-scrollbar">
                  {sortedRegions.map(region => {
                    const regionCountries = countriesByRegion[region].filter(c =>
                      c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                      c.iso2.toLowerCase().includes(searchQuery.toLowerCase()) ||
                      c.dialCode.includes(searchQuery)
                    );

                    if (regionCountries.length === 0) return null;

                    const isCollapsed = collapsedRegions.includes(region);
                    const allInRegionSelected = regionCountries.every(c => settings.enabled_countries.includes(c.iso2));
                    const selectedInRegion = regionCountries.filter(c => settings.enabled_countries.includes(c.iso2)).length;

                    return (
                      <div key={region} className="border border-slate-100 rounded-[4px] overflow-hidden bg-white shadow-none">
                        <div
                          onClick={() => toggleRegion(region)}
                          className="p-2.5 flex items-center justify-between cursor-pointer hover:bg-slate-50 transition-all"
                        >
                          <div className="flex items-center gap-3">
                            <div className="h-5 w-5 rounded bg-slate-100 flex items-center justify-center text-slate-400">
                              {isCollapsed ? <ChevronRight size={12} /> : <ChevronDown size={12} />}
                            </div>
                            <h4 className="font-black text-[#0F172A] uppercase tracking-widest text-[9px] !m-0">{region}</h4>
                            <span className="text-[9px] bg-[#004449]/10 px-1.5 py-0.5 rounded text-[#004449] font-black">
                              {selectedInRegion}/{regionCountries.length}
                            </span>
                          </div>

                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              let newEnabled = [...settings.enabled_countries];
                              if (allInRegionSelected) {
                                newEnabled = newEnabled.filter(iso => !regionCountries.find(c => c.iso2 === iso));
                              } else {
                                regionCountries.forEach(c => {
                                  if (!newEnabled.includes(c.iso2)) newEnabled.push(c.iso2);
                                });
                              }
                              updateSetting('enabled_countries', newEnabled);
                            }}
                            className={`text-[8px] font-black uppercase transition-all px-2 py-0.5 rounded-[3px] border ${allInRegionSelected ? 'text-rose-600 border-rose-100 bg-rose-50' : 'text-[#004449] border-[#004449]/20 bg-[#004449]/5'
                              }`}
                          >
                            {allInRegionSelected ? t.deselectAll : t.selectAll}
                          </button>
                        </div>

                        {!isCollapsed && (
                          <div className="p-3 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 bg-slate-50/50">
                            {regionCountries.map((country) => {
                              const isSelected = settings.enabled_countries.includes(country.iso2);
                              return (
                                <div
                                  key={country.iso2}
                                  onClick={() => toggleCountry(country.iso2)}
                                  className={`flex flex-col gap-3 p-3 rounded-xl border-2 transition-all cursor-pointer relative overflow-hidden group ${isSelected
                                    ? 'bg-white border-[#004449] ring-4 ring-[#004449]/5 shadow-sm'
                                    : 'bg-white border-slate-100 hover:border-slate-200'
                                    }`}
                                >
                                  <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2.5">
                                      <div className="text-xl">
                                        {iso2ToFlag(country.iso2)}
                                      </div>
                                      <span className={`text-[12px] font-black font-mono tracking-tighter transition-colors ${isSelected ? 'text-[#004449]' : 'text-slate-400'
                                        }`}>
                                        +{country.dialCode}
                                      </span>
                                    </div>

                                    <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all shrink-0 ${isSelected
                                      ? 'bg-[#004449] border-[#004449] text-white'
                                      : 'border-slate-200 shadow-inner bg-slate-50'
                                      }`}>
                                      {isSelected && <ShieldCheck size={12} strokeWidth={3} />}
                                    </div>
                                  </div>

                                  <div className="min-w-0">
                                    <h4 className={`text-[13px] font-bold tracking-tight truncate !m-0 leading-tight transition-colors ${isSelected ? 'text-slate-900' : 'text-slate-700'
                                      }`}>
                                      {country.name}
                                    </h4>
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            </SettingCard>
          </div>
        )}
      </div>

    </SettingsLayout>
  );
};

export default PhoneFieldSettings;
