import { useState, useRef, useMemo, useEffect } from 'react';
import type { DashboardData } from './types';
import {
  RefreshCw,
  Send,
  Zap,
  Plus,
  Trash2,
  Edit3,
  Power,
  Clock,
  CheckCircle,
  Type,
  Key,
  Hash,
  Globe,
  Smartphone,
  ShieldCheck
} from 'lucide-react';
import { toast } from 'sonner';

import { Separator } from './components/ui/separator';
import {
  SettingsLayout,
  SettingsHeader,
  ModernCardHeader,
  SettingCard,
  SettingInput,
  AdminButton,
  SecondaryButton,
  GhostButton,
  SaveWithStatus
} from './components/ui/settings-ui';
import { useSettingsSave } from './hooks/useSettingsSave';
import { Sheet, SheetContent } from './components/ui/sheet';

// Modern Modular Firebase SDK
import { initializeApp, getApp, getApps } from 'firebase/app';
import {
  getAuth,
  signInWithPhoneNumber,
  RecaptchaVerifier
} from 'firebase/auth';
import type { ConfirmationResult } from 'firebase/auth';

import PhoneInput from './components/ui/PhoneInput';
import type { PhoneInputRef } from './components/ui/PhoneInput';

export default function FirebaseSender({ data: rootData }: { data: DashboardData }) {

  const data = useMemo(() => rootData?.firebaseSenderData || { settings: {}, allAccounts: [], nonces: {} }, [rootData?.firebaseSenderData]);

  const [accounts, setAccounts] = useState<import('./types').FirebaseAccount[]>(data.allAccounts || []);
  const [settings, setSettings] = useState<Record<string, string>>(data.settings || {});
  const [accountName, setAccountName] = useState(data.settings?.account_name || 'Default Account');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const [isTesting, setIsTesting] = useState(false);
  const [isVerifying, setIsVerifying] = useState(false);
  const [otp, setOtp] = useState('');
  const [showOtpInput, setShowOtpInput] = useState(false);
  const [confirmationResult, setConfirmationResult] = useState<ConfirmationResult | null>(null);

  const { saveStatus, hasUnsavedChanges, isSaving, handleSave, markDirty } = useSettingsSave({
    onSave: async () => {
      try {
        const response = await fetch(`${rootData.global.apiRestUrl}/accounts/firebase`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': rootData.global.wpRestNonce
          },
          body: JSON.stringify({
            account_name: accountName,
            config: settings,
            id: editingId
          })
        });

        const result = await response.json();
        if (result.success) {
          window.dispatchEvent(new CustomEvent('wawp-refresh-data', {
            detail: { section: 'firebase-sender' }
          }));
          return true;
        }
        return false;
      } catch {
        return false;
      }
    }
  });

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

  const [prevData, setPrevData] = useState(data);
  if (data !== prevData) {
    setPrevData(data);
    if (data.options) setSettings(data.options);
    if (data.allAccounts) setAccounts(data.allAccounts);
  }

  const phoneInputRef = useRef<PhoneInputRef>(null);
  const recaptchaVerifierRef = useRef<RecaptchaVerifier | null>(null);

  const dStat = rootData?.domainStatus;
  const cSec = rootData?.global?.section || rootData?.currentSection;
  if (dStat && dStat !== 'active' && cSec !== 'account') return null;

  const handleInputChange = (field: string, value: string) => {
    setSettings(prev => ({ ...prev, [field]: value }));
    markDirty();
  };

  const handleAccountNameChange = (val: string) => {
    setAccountName(val);
    markDirty();
  };


  const deleteAccount = async (id: number) => {
    if (!confirm('Are you sure you want to delete this account?')) return;
    try {
      const resp = await fetch(`${rootData.global.apiRestUrl}/accounts/firebase/${id}`, {
        method: 'DELETE',
        headers: {
          'X-WP-Nonce': rootData.global.wpRestNonce
        }
      });
      const result = await resp.json();
      if (result.success) {
        setAccounts(prev => prev.filter(a => a.id !== id));
        toast.success('Account deleted');
      }
    } catch { toast.error('Error deleting'); }
  };

  const toggleAccount = async (id: number) => {
    try {
      const resp = await fetch(`${rootData.global.apiRestUrl}/accounts/firebase/${id}/toggle`, {
        method: 'POST',
        headers: {
          'X-WP-Nonce': rootData.global.wpRestNonce
        }
      });
      const result = await resp.json();
      if (result.success) {
        window.location.reload();
      }
    } catch { toast.error('Error toggling'); }
  };

  const validateAccount = async (id: number) => {
    try {
      await fetch(`${rootData.global.apiRestUrl}/accounts/firebase/validate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': rootData.global.wpRestNonce
        },
        body: JSON.stringify({ id })
      });
    } catch { console.error('Silent fail validation update'); }
  };

  const startNewAccount = () => {
    setEditingId(null);
    setAccountName('New Project');
    setSettings({ active: 'on' });
    setIsDialogOpen(true);
    setShowOtpInput(false);
  };

  const editAccount = (acc: import('./types').FirebaseAccount) => {
    setEditingId(acc.id);
    setAccountName(acc.account_name);
    setSettings(acc.config || {});
    setIsDialogOpen(true);
    setShowOtpInput(false);
  };

  const initFirebase = () => {
    const firebaseConfig = {
      apiKey: settings.apiKey || settings.api_key,
      authDomain: settings.authDomain,
      projectId: settings.projectId,
      storageBucket: settings.storageBucket,
      messagingSenderId: settings.messagingSenderId,
      appId: settings.appId,
      measurementId: settings.measurementId
    };

    if (getApps().length > 0) {
      const app = getApp();
      if (app.options.apiKey !== firebaseConfig.apiKey) {
        return initializeApp(firebaseConfig, 'app-' + (editingId || Date.now()));
      }
      return app;
    }
    return initializeApp(firebaseConfig);
  };

  const sendTestOTP = async () => {
    if (!phoneInputRef.current) return;
    const fullPhone = phoneInputRef.current.getNumber();
    if (!fullPhone || fullPhone.length < 7) {
      toast.error('Enter valid phone number.');
      return;
    }
    if (!settings.apiKey && !settings.api_key) {
      toast.error('Missing API Key.');
      return;
    }

    setIsTesting(true);
    const loadingToast = toast.loading('Initializing Firebase...');
    try {
      const app = initFirebase();
      const auth = getAuth(app);
      auth.languageCode = 'ar';

      const containerId = 'recaptcha-container';
      let container = document.getElementById(containerId);
      if (!container) {
        container = document.createElement('div');
        container.id = containerId;
        document.body.appendChild(container);
      }

      if (!recaptchaVerifierRef.current) {
        recaptchaVerifierRef.current = new RecaptchaVerifier(auth, containerId, { 'size': 'invisible' });
      }

      const confirmation = await signInWithPhoneNumber(auth, fullPhone, recaptchaVerifierRef.current);
      setConfirmationResult(confirmation);
      setShowOtpInput(true);
      toast.success('SMS sent!', { id: loadingToast });
    } catch (error) {
      toast.error('Firebase Error: ' + ((error as Error).message || 'Unknown'), { id: loadingToast });
    } finally { setIsTesting(false); }
  };

  const verifyOTP = async () => {
    if (!otp || otp.length < 6) return toast.error('Enter 6-digit code.');
    if (!confirmationResult) return toast.error('Session expired.');

    setIsVerifying(true);
    const loadingToast = toast.loading('Verifying code...');
    try {
      await confirmationResult.confirm(otp);
      toast.success('Verified!', { id: loadingToast });
      setShowOtpInput(false);
      setOtp('');
      if (editingId) {
        await validateAccount(editingId);
        setAccounts(prev => prev.map(a => a.id === editingId ? { ...a, validated: 1 } : a));
      }
    } catch (error) {
      toast.error('Invalid code: ' + (error as Error).message, { id: loadingToast });
    } finally { setIsVerifying(false); }
  };

  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-6 animate-in fade-in duration-500 pb-12">
        <SettingsHeader
          title="Firebase SMS Authentication"
          description="Use Google Firebase to send SMS verification codes globally (Requires API Key)."
          backUrl="admin.php?page=wawp&wawp_section=senders"
          className="mb-8"
        >
          <SecondaryButton onClick={startNewAccount} className="uppercase tracking-widest px-6" icon={Plus}>
            Add Account
          </SecondaryButton>
        </SettingsHeader>

        <SettingCard className="p-0 overflow-hidden border-slate-100 shadow-sm">
          <ModernCardHeader
            iconPath={`${rootData?.global?.pluginUrl}assets/img/senders/firebase.svg`}
            title="Firebase Accounts"
            description={<span className="text-xs uppercase tracking-widest text-[#004449] font-bold">Manage configurations and validation status</span>}
          />
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-slate-50/50 border-y border-slate-100">
                  <th className="px-6 py-4 text-[10px] uppercase tracking-widest font-bold text-slate-400">Default Sender</th>
                  <th className="px-6 py-4 text-[10px] uppercase tracking-widest font-bold text-slate-400">Account Name</th>
                  <th className="px-6 py-4 text-[10px] uppercase tracking-widest font-bold text-slate-400">System Status</th>
                  <th className="px-6 py-4 text-[10px] uppercase tracking-widest font-bold text-slate-400 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {accounts.length > 0 ? accounts.map((acc) => (
                  <tr key={acc.id} className="group hover:bg-slate-50/50 transition-colors">
                    <td className="px-6 py-4">
                      {acc.is_active ? (
                        <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-600 text-white text-[10px] font-bold uppercase tracking-widest shadow-sm">
                          <Power className="w-3 h-3" /> Selected
                        </span>
                      ) : (
                        <GhostButton onClick={() => toggleAccount(acc.id)} className="px-3 text-[10px] font-bold uppercase tracking-widest text-slate-400 hover:text-[#004449] hover:bg-slate-100">
                          Set Default
                        </GhostButton>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="font-bold text-slate-700 text-sm">{acc.account_name}</div>
                      <div className="font-mono text-[9px] text-slate-400 mt-1">{acc.config?.projectId || 'No ID'}</div>
                    </td>
                    <td className="px-6 py-4">
                      {acc.validated ? (
                        <span className="inline-flex items-center gap-1.5 text-emerald-600 text-[10px] font-bold uppercase tracking-widest">
                          <CheckCircle className="w-3.5 h-3.5" /> Active
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 text-amber-500 text-[10px] font-bold uppercase tracking-widest">
                          <Clock className="w-3.5 h-3.5" /> Pending Setup
                        </span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex justify-end gap-2">
                        <SecondaryButton onClick={() => editAccount(acc)} className="px-3 text-[10px] font-bold uppercase tracking-widest text-blue-600 border-blue-100 hover:bg-blue-50 rounded-[4px]" icon={Edit3}>
                          Edit & Test
                        </SecondaryButton>
                        <GhostButton onClick={() => deleteAccount(acc.id)} className="w-8 p-0 text-rose-500 hover:text-rose-600 hover:bg-rose-50 rounded-[4px]" icon={Trash2}>
                          {null}
                        </GhostButton>
                      </div>
                    </td>
                  </tr>
                )) : (
                  <tr>
                    <td colSpan={4} className="px-6 py-12 text-center text-slate-400 text-sm italic">
                      No accounts configured.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </SettingCard>

        {/* Dialog: Add/Edit Account */}
        <Sheet open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <SheetContent side="right" className="w-full lg:max-w-[calc(100%-280px)] xl:max-w-[1200px] p-0 overflow-hidden border-none shadow-2xl flex flex-col h-full">

            <div className="bg-slate-50 border-b border-slate-100 sticky top-0 z-10">
              <ModernCardHeader
                title={editingId ? 'Edit Firebase Account' : 'Connect New Project'}
                description={
                  <span className="text-xs uppercase tracking-widest text-[#004449] font-bold">
                    {editingId ? 'Update your project credentials and validate connection' : 'Setup your Google Firebase credentials for OTP sending'}
                  </span>
                }
                iconPath={`${rootData?.global?.pluginUrl}assets/img/senders/firebase.svg`}
              />
            </div>

            <div className="flex-1 overflow-y-auto">
              <div className="p-6 space-y-8">
                {/* Identity Information */}
                <div className="space-y-4">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                    <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">Identity</span>
                  </div>
                    <SettingInput
                      label="Account Friendly Name"
                      value={accountName}
                      onChange={handleAccountNameChange}
                      placeholder=""
                      icon={Type}
                    />
                </div>

                {/* Credentials */}
                <div className="space-y-6">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                    <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">Firebase Configuration</span>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-5">
                    <SettingInput
                      label="API Key (Web SDK)"
                      value={settings.apiKey || settings.api_key || ''}
                      onChange={(val: string) => handleInputChange('apiKey', val)}
                      placeholder=""
                      icon={Key}
                    />
                    <SettingInput
                      label="Project ID"
                      value={settings.projectId || ''}
                      onChange={(val: string) => handleInputChange('projectId', val)}
                      placeholder=""
                      icon={Hash}
                    />
                    <SettingInput
                      label="Auth Domain"
                      value={settings.authDomain || ''}
                      onChange={(val: string) => handleInputChange('authDomain', val)}
                      placeholder=""
                      icon={Globe}
                    />
                    <SettingInput
                      label="App ID"
                      value={settings.appId || ''}
                      onChange={(val: string) => handleInputChange('appId', val)}
                      placeholder=""
                      icon={Smartphone}
                    />

                    <div className="md:col-span-2 pt-2">
                      <Separator className="mb-6 opacity-50" />
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <SettingInput
                          label="Storage Bucket"
                          value={settings.storageBucket || ""}
                          onChange={(val: string) => handleInputChange("storageBucket", val)}
                          placeholder=""
                          icon={Globe}
                        />
                        <SettingInput
                          label="Messaging Sender ID"
                          value={settings.messagingSenderId || ""}
                          onChange={(val: string) => handleInputChange("messagingSenderId", val)}
                          placeholder=""
                          icon={Hash}
                        />
                        <SettingInput
                          label="Measurement ID"
                          value={settings.measurementId || ""}
                          onChange={(val: string) => handleInputChange("measurementId", val)}
                          placeholder=""
                          icon={Type}
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* Validation Test (Only if saved/editing) */}
                <div className={`p-5 rounded-xl border ${showOtpInput ? 'bg-emerald-50 border-emerald-100' : 'bg-slate-50 border-slate-100'}`}>
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2">
                      <Zap className={`w-4 h-4 ${showOtpInput ? 'text-emerald-600' : 'text-[#004449]'}`} />
                      <span className="text-[11px] font-bold uppercase tracking-wider text-slate-700">Account Validation Test</span>
                    </div>
                    {editingId && (
                      <div className="px-2 py-0.5 rounded-full bg-white border border-slate-100 text-[9px] font-bold text-slate-400 uppercase tracking-tighter shadow-sm">
                        Real-time Verification
                      </div>
                    )}
                  </div>

                  {!showOtpInput ? (
                    <div className="space-y-3">
                      <div className="flex gap-2">
                        <div className="flex-1">
                          <PhoneInput ref={phoneInputRef} hideMessage className="rounded-lg border border-slate-200 text-sm bg-white" placeholder="Enter phone for test" />
                        </div>
                        <AdminButton onClick={sendTestOTP} disabled={isTesting} className="px-5 active:scale-95 transition-all" icon={isTesting ? RefreshCw : Send} loading={isTesting}>
                          {null}
                        </AdminButton>
                      </div>
                      <p className="text-[10px] text-slate-400 leading-relaxed italic">Click the icon to send a test OTP. This must succeed to activate the "Active" status for this account.</p>
                    </div>
                  ) : (
                    <div className="space-y-4 animate-in zoom-in-95">
                      <div className="flex gap-2">
                        <SettingInput
                          label="OTP Code"
                          value={otp}
                          onChange={setOtp}
                          placeholder="000000"
                          icon={ShieldCheck}
                          className="grow"
                          labelHidden
                        />
                        <AdminButton onClick={verifyOTP} disabled={isVerifying} className="bg-emerald-600 hover:bg-emerald-700 px-8" loading={isVerifying}>
                          Verify
                        </AdminButton>
                      </div>
                      <GhostButton onClick={() => setShowOtpInput(false)} className="h-4 p-0 text-[10px] uppercase font-bold text-emerald-600 underline-offset-4">Change number or resend</GhostButton>
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div className="p-6 bg-slate-50 border-t border-slate-100 sticky bottom-0 z-10 flex items-center justify-between gap-4">
              <GhostButton onClick={() => setIsDialogOpen(false)} className="rounded-lg font-bold text-slate-500 hover:bg-white active:scale-95 transition-all border border-transparent hover:border-slate-200 px-6">
                Close
              </GhostButton>
              <SaveWithStatus
                saveStatus={saveStatus}
                hasUnsavedChanges={hasUnsavedChanges}
                isSaving={isSaving}
                onSave={() => handleSave(false)}
                t={{
                  saveChanges: editingId ? 'Update Connection' : 'Save Connection'
                }}
              />
            </div>
            <div id="recaptcha-container"></div>
          </SheetContent>
        </Sheet>
      </div>
    </SettingsLayout>
  );
}
