import { useState, useCallback, useEffect } from 'react';
import type { DashboardData } from './types';

import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './components/ui/table';
import { Badge } from './components/ui/badge';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from './components/ui/dropdown-menu';
import { Plus, RefreshCw, Trash2, Edit, Send, MoreHorizontal, User, Smartphone, PenBox, Type } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from './components/ui/dialog';
import { Sheet, SheetContent } from './components/ui/sheet';
import { Label } from './components/ui/label';
import { MultiSelectTagify } from './components/ui/multi-select-tagify';
import { toast } from 'sonner';
import { CheckCircle2, Key, Hash } from 'lucide-react';
import {
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SecondaryButton,
  GhostButton,
  ModernCardHeader,
  SettingCard,
  SettingInput,
  StatusMessage,
  SaveWithStatus
} from './components/ui/settings-ui';
import { useSettingsSave } from './hooks/useSettingsSave';

interface InstanceData {
  id: number;
  name: string;
  instance_id: string;
  access_token: string;
  status: string;
  message: string;
}

export default function WhatsAppWebSender({ data: dashboardData }: { data: DashboardData }) {

  const t = (key: string, fallback: string): string => {
    const val = (dashboardData?.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  };

  const [instances, setInstances] = useState<InstanceData[]>(dashboardData?.instancesData?.instances || []);

  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isTestSuccessModalOpen, setIsTestSuccessModalOpen] = useState(false);
  const [isMeModalOpen, setIsMeModalOpen] = useState(false);
  const [meData, setMeData] = useState<unknown>(null);
  const [currentInstance, setCurrentInstance] = useState<InstanceData | null>(null);

  const [isAdding, setIsAdding] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);

  // Form states
  const [formData, setFormData] = useState({ name: '', instance_id: '', access_token: '', phone_number: '', message: '' });

  const [mappings, setMappings] = useState({
    login: [] as string[],
    signup: [] as string[],
    checkout: [] as string[],
    general: [] as string[],
    notif_user: [] as string[],
    notif_admin: [] as string[],
  });
  const [features, setFeatures] = useState({
    otp_login: true,
    otp_signup: true,
    otp_checkout: true,
    notifications: true,
  });
  const fetchInstances = useCallback(async () => {
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'GET',
        headers: { 'X-WP-Nonce': dashboardData.global.wpRestNonce }
      });
      const result = await response.json();
      if (result.success) {
        setInstances(result.data || []);
      }
    } catch (error) {
      console.error('Failed to load instances', error);
    }
  }, [dashboardData.global.apiRestUrl, dashboardData.global.wpRestNonce]);

  useEffect(() => {
    const timer = setTimeout(() => {
      fetchInstances();
    }, 0);
    return () => clearTimeout(timer);
  }, [fetchInstances]);

  const syncData = useCallback(() => {
    if (!dashboardData) return;

    const currentInstances = dashboardData.instancesData?.instances || instances;
    const onlineInst = currentInstances.find((i: InstanceData) => i.status?.toLowerCase() === 'online') || currentInstances[0];
    const onlineId = onlineInst?.id || '';

    const resolveToInternalId = (val: unknown): string[] => {
      let rawList: string[] = [];
      if (Array.isArray(val)) rawList = val.map(String).filter(Boolean);
      else if (typeof val === 'string' && val.trim() !== '') rawList = val.split(',').filter(Boolean);
      else if (val !== undefined && val !== null && val !== '' && val !== 0) rawList = [String(val)];
      
      const resolved = rawList.map(item => {
        const match = currentInstances.find((inst: InstanceData) => String(inst.id) === item || inst.instance_id === item);
        return match ? String(match.id) : item;
      });
      // Remove duplicates
      return Array.from(new Set(resolved));
    };

    const savedLogin = resolveToInternalId(dashboardData.otp?.instance);
    const savedSignup = resolveToInternalId(dashboardData.signup?.selected_instance);
    const savedCheckout = resolveToInternalId(dashboardData.checkout_instance);
    const savedNotifUser = resolveToInternalId(dashboardData.notif?.selected_instance_ids);
    const savedNotifAdmin = resolveToInternalId(dashboardData.notif?.admin_selected_instance_ids);
    const savedGeneral = resolveToInternalId(dashboardData.general_instance);

    setMappings({
      login: savedLogin.length > 0 ? savedLogin : (onlineId ? [String(onlineId)] : []),
      signup: savedSignup.length > 0 ? savedSignup : (onlineId ? [String(onlineId)] : []),
      checkout: savedCheckout.length > 0 ? savedCheckout : (onlineId ? [String(onlineId)] : []),
      notif_user: savedNotifUser.length > 0 ? savedNotifUser : (onlineId ? [String(onlineId)] : []),
      notif_admin: savedNotifAdmin.length > 0 ? savedNotifAdmin : (onlineId ? [String(onlineId)] : []),
      general: savedGeneral.length > 0 ? savedGeneral : (onlineId ? [String(onlineId)] : [])
    });

    setFeatures({
      notifications: !!dashboardData.notif?.enabled,
      otp_login: !!(dashboardData.otp?.enabled && dashboardData.otp?.login_enabled),
      otp_signup: !!(dashboardData.otp?.enabled && dashboardData.otp?.signup_enabled),
      otp_checkout: !!(dashboardData.otp?.enabled && dashboardData.otp?.checkout_enabled),
    });
  }, [dashboardData, instances]);

  useEffect(() => {
    const timer = setTimeout(() => {
      syncData();
    }, 0);
    return () => clearTimeout(timer);
  }, [syncData]);

  const { saveStatus, hasUnsavedChanges, isSaving: isSavingMappings, handleSave, markDirty } = useSettingsSave({
    onSave: async () => {
      try {
        const response = await fetch(`${dashboardData.global.settingsRestUrl}${dashboardData.global.settingsRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': dashboardData.global.wpRestNonce
          },
          body: JSON.stringify({
            settings: {
              wawp_otp_settings: {
                ...dashboardData.otp,
                instance: mappings.login.join(',')
              },
              wawp_signup_settings: {
                ...dashboardData.signup,
                selected_instance: mappings.signup.join(',')
              },
              wawp_checkout_settings: {
                ...dashboardData.checkout,
                wawp_selected_instance: mappings.checkout.join(',')
              },
              wawp_general_instance: mappings.general.join(','),
              wawp_notif_selected_instance_ids: mappings.notif_user.join(','),
              wawp_notif_admin_selected_instance_ids: mappings.notif_admin.join(',')
            }
          })
        });
        const result = await response.json();
        if (result.success) {
          window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'whatsapp-web-sender' } }));
          return true;
        }
        return false;
      } catch (error) {
        console.error('WhatsApp mappings save error:', error);
        return false;
      }
    }
  });

  const updateMappings = (key: keyof typeof mappings, value: string[]) => {
    setMappings(prev => ({ ...prev, [key]: value }));
    markDirty();
  };




  const handleAddInstance = async () => {
    if (isAdding) return;
    setIsAdding(true);
    const loadingToast = toast.loading('Adding instance...');
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          account_name: formData.name,
          config: {
            instance_id: formData.instance_id,
            access_token: formData.access_token
          }
        })
      });
      const result = await response.json();
      if (result.success) {
        toast.success('Instance added successfully', { id: loadingToast });
        setIsAddModalOpen(false);
        setFormData({ ...formData, name: '', instance_id: '', access_token: '' });
        fetchInstances();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'whatsapp-web-sender' } }));
      } else {
        toast.error(result.message || 'Failed to add instance', { id: loadingToast });
      }
    } catch {
      toast.error('An error occurred', { id: loadingToast });
    } finally {
      setIsAdding(false);
    }
  };

  const handleEditInstance = async () => {
    if (!currentInstance || isUpdating) return;
    setIsUpdating(true);
    const loadingToast = toast.loading('Updating instance...');
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          id: currentInstance.id,
          account_name: formData.name,
          config: {
            instance_id: formData.instance_id,
            access_token: formData.access_token
          }
        })
      });
      const result = await response.json();
      if (result.success) {
        toast.success('Instance updated successfully', { id: loadingToast });
        setIsEditModalOpen(false);
        fetchInstances();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'whatsapp-web-sender' } }));
      } else {
        toast.error(result.message || 'Failed to update instance', { id: loadingToast });
      }
    } catch {
      toast.error('An error occurred', { id: loadingToast });
    } finally {
      setIsUpdating(false);
    }
  };

  const handleDeleteInstance = useCallback(async (id: number) => {
    if (!confirm('Are you sure you want to delete this instance?')) return;
    const loadingToast = toast.loading('Deleting instance...');
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web/${id}${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'DELETE',
        headers: { 'X-WP-Nonce': dashboardData.global.wpRestNonce }
      });
      const result = await response.json();
      if (result.success) {
        toast.success('Instance deleted', { id: loadingToast });
        fetchInstances();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'whatsapp-web-sender' } }));
      } else {
        toast.error(result.message || 'Failed to delete instance', { id: loadingToast });
      }
    } catch {
      toast.error('An error occurred', { id: loadingToast });
    }
  }, [dashboardData, fetchInstances]);

  const handleUpdateStatus = useCallback(async (inst: InstanceData) => {
    const loadingToast = toast.loading('Refreshing instance status...');
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web/ops${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          op: 'status',
          instance_id: inst.instance_id,
          access_token: inst.access_token
        })
      });
      const result = await response.json();
      if (result.success) {
        toast.success('Status updated', { id: loadingToast });
        fetchInstances();
      } else {
        toast.error(result.message || 'Failed to check status', { id: loadingToast });
      }
    } catch {
      toast.error('An error occurred', { id: loadingToast });
    }
  }, [dashboardData, fetchInstances]);

  const handleSendTestDelivery = useCallback(async (inst: InstanceData) => {
    const targetNumber = '447441429009';
    const greetings = ['Hi', 'Hello', 'Hey', 'Greetings'];
    const greeting = greetings[Math.floor(Math.random() * greetings.length)];
    const randomRef = Math.random().toString(36).substring(7).toUpperCase();
    const randomCode = Math.floor(1000 + Math.random() * 9000);

    const message = `${greeting} From Wawp Plugin.\nThis test message and my site can work now.\n\n[Ref: ${randomRef}, Code: ${randomCode}]`;

    const loadingToast = toast.loading('Sending secure test delivery...');
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web/ops${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          op: 'test',
          instance_id: inst.instance_id,
          access_token: inst.access_token,
          phone_number: targetNumber,
          message: message
        })
      });
      const result = await response.json();
      if (result.success) {
        toast.success('Test message sent', { id: loadingToast });
        setIsTestSuccessModalOpen(true);
      } else {
        toast.error(result.message || 'Failed to send test message', { id: loadingToast });
      }
    } catch {
      toast.error('An error occurred', { id: loadingToast });
    }
  }, [dashboardData]);

  const handleMe = useCallback(async (inst: InstanceData) => {
    const loadingToast = toast.loading('Fetching account data...');
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web/ops`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          op: 'me',
          instance_id: inst.instance_id,
          access_token: inst.access_token
        })
      });
      const result = await response.json();
      if (result.success) {
        setMeData(result.data);
        setIsMeModalOpen(true);
        toast.success('Data fetched successfully', { id: loadingToast });
      } else {
        toast.error(result.message || 'Failed to fetch data.', { id: loadingToast });
      }
    } catch {
      toast.error('An error occurred while fetching data.', { id: loadingToast });
    }
  }, [dashboardData]);

  const getStatusBadge = (status: string, message: string) => {
    let st = status?.toLowerCase() || 'unknown';
    let bg = 'bg-slate-100';
    let text = 'text-slate-600';
    let dot = 'bg-slate-400';

    // Per user request: If WORKING, show as ONLINE
    if (st === 'working' || st === 'online' || st === 'ready') {
      st = 'online';
      bg = 'bg-emerald-50';
      text = 'text-emerald-700';
      dot = 'bg-emerald-500';
    } else if (st === 'offline' || st === 'failed' || st === 'stopped') {
      bg = 'bg-rose-50';
      text = 'text-rose-700';
      dot = 'bg-rose-500';
    } else if (st === 'checking' || st === 'paused') {
      bg = 'bg-amber-50';
      text = 'text-amber-700';
      dot = 'bg-amber-500';
    } else if (st === 'scan_qr_code' || st === 'scan qr') {
      bg = 'bg-sky-50';
      text = 'text-sky-700';
      dot = 'bg-sky-500';
    }

    const isError = st === 'offline' || st === 'failed' || st === 'stopped';

    return (
      <div className="flex flex-col gap-1.5 pt-1">
        <div className={`inline-flex items-center gap-2 px-2 py-0.5 rounded-[4px] border-none ${bg} ${text} w-fit`}>
          <span className={`w-1.5 h-1.5 rounded-full ${st === 'online' ? 'animate-pulse' : ''} ${dot}`} />
          <span className="text-[10px] font-black uppercase tracking-wider leading-none">{st === 'scan qr' ? 'Scan QR' : st}</span>
        </div>
        {isError && message && <span className="text-[10px] font-medium text-slate-400 max-w-[140px] truncate block px-0.5" title={message}>{message}</span>}
      </div>
    );
  };


  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-4 animate-in fade-in duration-500">

        {/* Header */}
        <SettingsHeader
          title={t('waWebTitle', 'WhatsApp Web')}
          description={t('waWebDesc', 'Connect your personal WhatsApp for automated orders notifications.')}
          backUrl="admin.php?page=wawp&wawp_section=senders"
          className="mb-6"
        >
          <SaveWithStatus
            saveStatus={saveStatus}
            hasUnsavedChanges={hasUnsavedChanges}
            isSaving={isSavingMappings}
            onSave={() => handleSave(false)}
          />
        </SettingsHeader>

        {/* Connected Numbers Card */}
        <SettingCard className="p-0 overflow-hidden">
          <ModernCardHeader
            iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/whatsapp.svg`}
            title={
              <>
                {t('connectedNumbers', 'Connected Numbers')}
                <a href="admin.php?page=wawp&wawp_section=account" className="text-xs text-indigo-600 hover:text-indigo-800 flex items-center gap-1 ml-2 font-bold no-underline group translate-y-[1px]">
                  <RefreshCw className="w-3 h-3 group-hover:rotate-180 transition-transform duration-500" /> {t('sync', 'Sync')}
                </a>
              </>
            }
            description={
              <span className="uppercase tracking-wider">
                {t('waWebSlotsDesc', 'Connect and manage your WhatsApp Web instances for automated notifications.')}
              </span>
            }
            rightAction={
              (
                <Sheet open={isAddModalOpen} onOpenChange={setIsAddModalOpen}>
                  <DialogTrigger asChild>
                    <AdminButton onClick={() => setIsAddModalOpen(true)} icon={Plus}>
                      {t('addNewInstance', 'Add New Instance')}
                    </AdminButton>
                  </DialogTrigger>
                  <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="flex-1 overflow-y-auto">
                      <ModernCardHeader
                        title={t('addNewInstanceManually', 'Connect Instance')}
                        description={(
                          <>
                            Connect your phone via <a href="https://wawp.net/account/connect" target="_blank" rel="noopener noreferrer" className="text-[#004449] font-bold underline underline-offset-2">Wawp.net</a> or add credentials manually.
                          </>
                        )}
                        iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/whatsapp.svg`}
                      />
                      <div className="p-6 md:p-8 space-y-8">
                        <div className="p-5 rounded-xl border border-emerald-100 bg-emerald-50/30 flex items-start gap-4">
                          <div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center shrink-0">
                            <Smartphone className="w-5 h-5 text-emerald-600" />
                          </div>
                          <div className="space-y-1">
                            <h4 className="text-[13px] font-black text-slate-800 uppercase tracking-tight">Rapid Connection</h4>
                            <p className="text-[11px] text-slate-500 font-medium leading-relaxed">
                              Open your WAWP app, go to Settings {'>'} Link Device and scan the QR.
                            </p>
                          </div>
                          <SecondaryButton
                            onClick={() => window.open('https://wawp.net/dashboard', '_blank')}
                            className="ml-auto shrink-0 text-[10px] h-8"
                          >
                            Get QR Code
                          </SecondaryButton>
                        </div>

                        <div className="space-y-6">
                          <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Manual Credentials</label>
                          <div className="space-y-5">
                            <SettingInput
                              label={t('name', 'Friendly Name')}
                              value={formData.name}
                              onChange={(val: string) => setFormData({ ...formData, name: val })}
                              placeholder=""
                              icon={Type}
                            />
                            <SettingInput
                              label={t('instanceId', 'Instance ID')}
                              value={formData.instance_id}
                              onChange={(val: string) => setFormData({ ...formData, instance_id: val })}
                              placeholder=""
                              icon={Hash}
                            />
                            <SettingInput
                              label={t('accessToken', 'Access Token')}
                              value={formData.access_token}
                              onChange={(val: string) => setFormData({ ...formData, access_token: val })}
                              placeholder=""
                              icon={Key}
                              type="password"
                            />
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="p-6 bg-slate-50 border-t border-slate-100 flex gap-3">
                      <SecondaryButton onClick={() => setIsAddModalOpen(false)} className="flex-1">
                        {t('close', 'Close')}
                      </SecondaryButton>
                      <AdminButton
                        onClick={handleAddInstance}
                        loading={isAdding}
                        icon={CheckCircle2}
                        className="flex-[2]"
                      >
                        {t('save', 'Connect')}
                      </AdminButton>
                    </div>
                  </SheetContent>
                </Sheet>
              )}
          />
          <div className="p-0">
            {/* Mobile View: Cards */}
            <div className="sm:hidden space-y-3 p-4">
              {instances.length === 0 ? (
                <div className="flex flex-col items-center justify-center text-slate-400 opacity-60 py-10 border-2 border-dashed border-slate-100 rounded-xl">
                  <p className="text-sm font-bold">{t('noInstancesFound', 'No Instances Found')}</p>
                </div>
              ) : (
                instances.map((inst) => (
                  <div key={inst.id} className="p-4 rounded-xl border border-slate-100 bg-white shadow-sm space-y-3">
                    <div className="flex items-center justify-between">
                      <div className="flex flex-col">
                        <span className="text-sm font-bold text-slate-900">{inst.name}</span>
                        <span className="text-[10px] font-mono text-slate-400 uppercase">{inst.instance_id}</span>
                      </div>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <GhostButton size="icon-sm" className="hover:bg-slate-50 border border-slate-100 rounded-lg">
                            <MoreHorizontal className="h-4 w-4 text-slate-400" />
                          </GhostButton>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-52 p-1.5 rounded-[5px] shadow-none border-slate-100">
                          <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[3px] text-xs font-bold" onClick={() => handleSendTestDelivery(inst)}>
                            <Send className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('sendTestMessage', 'Send Test Delivery')}
                          </DropdownMenuItem>
                          <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[3px] text-xs font-bold" onClick={() => handleUpdateStatus(inst)}>
                            <RefreshCw className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('checkConnection', 'Force Status Link')}
                          </DropdownMenuItem>
                          <div className="h-px bg-slate-50 my-1" />
                          <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[3px] text-xs font-bold" onClick={() => { setCurrentInstance(inst); setFormData({ ...formData, name: inst.name, instance_id: inst.instance_id, access_token: inst.access_token }); setIsEditModalOpen(true); }}>
                            <Edit className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('edit', 'Modify Credentials')}
                          </DropdownMenuItem>
                          <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[3px] text-xs font-bold" onClick={() => handleMe(inst)}>
                            <User className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('aboutData', 'Inspect Session Data')}
                          </DropdownMenuItem>
                          <div className="h-px bg-slate-50 my-1" />
                          <DropdownMenuItem className="text-rose-600 focus:bg-rose-50 focus:text-rose-700 cursor-pointer py-2 px-3 rounded-[3px] text-xs font-bold" onClick={() => handleDeleteInstance(inst.id)}>
                            <Trash2 className="mr-2.5 h-3.5 w-3.5" /> {t('delete', 'Disconnect Instance')}
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                    <div className="flex items-center justify-between pt-2 border-t border-slate-50">
                      <div className="flex flex-col gap-0.5">
                        <span className="text-[9px] font-black uppercase tracking-widest text-slate-400">Security Token</span>
                        <span className="font-mono text-[11px] text-slate-500">••••••••{inst.access_token?.slice(-4)}</span>
                      </div>
                      <div className="text-right">
                        {getStatusBadge(inst.status, inst.message)}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Desktop View: Table */}
            <div className="max-sm:hidden overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-slate-50/50 hover:bg-slate-50 transition-none border-b border-slate-100">
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest pl-6">{t('name', 'Name')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest">{t('instanceId', 'Instance ID')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest">{t('accessToken', 'Access Token')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest">{t('status', 'Status')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest text-right pr-6">{t('actions', 'Actions')}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {instances.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={5} className="h-32 text-center">
                        <div className="flex flex-col items-center justify-center text-slate-400 opacity-60">
                          <p className="text-sm font-bold">{t('noInstancesFound', 'No Instances Found')}</p>
                          <p className="text-xs mt-1">Connect your first WhatsApp number to begin.</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    instances.map((inst) => (
                      <TableRow key={inst.id} className="group hover:bg-slate-50/30 transition-colors border-b border-slate-50 last:border-0 font-medium">
                        <TableCell className="text-slate-900 text-sm py-4 pl-6">{inst.name}</TableCell>
                        <TableCell className="font-mono text-[12px] text-slate-500">{inst.instance_id}</TableCell>
                        <TableCell className="font-mono text-[12px] text-slate-400 opacity-60">••••••••{inst.access_token?.slice(-4)}</TableCell>
                        <TableCell>{getStatusBadge(inst.status, inst.message)}</TableCell>
                        <TableCell className="text-right pr-6">
                          <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                            <GhostButton 
                              size="icon-sm" 
                              title={t('sendTestMessage', 'Send Test Delivery')}
                              onClick={() => handleSendTestDelivery(inst)}
                              className="hover:bg-emerald-50 hover:text-emerald-600 border border-transparent hover:border-emerald-100 rounded-[5px]"
                            >
                              <Send className="h-3.5 w-3.5" />
                            </GhostButton>
                            
                            <GhostButton 
                              size="icon-sm" 
                              title={t('edit', 'Modify Credentials')}
                              onClick={() => { setCurrentInstance(inst); setFormData({ ...formData, name: inst.name, instance_id: inst.instance_id, access_token: inst.access_token }); setIsEditModalOpen(true); }}
                              className="hover:bg-blue-50 hover:text-blue-600 border border-transparent hover:border-blue-100 rounded-[5px]"
                            >
                              <Edit className="h-3.5 w-3.5" />
                            </GhostButton>

                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <GhostButton size="icon-sm" className="hover:bg-white border border-transparent hover:border-slate-200 rounded-[5px] transition-all">
                                  <MoreHorizontal className="h-4 w-4 text-slate-400 group-hover:text-slate-900" />
                                </GhostButton>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end" className="w-52 p-1.5 rounded-[8px] shadow-2xl border-slate-100 z-[999999]">
                                <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[5px] text-xs font-bold" onClick={() => handleSendTestDelivery(inst)}>
                                  <Send className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('sendTestMessage', 'Send Test Delivery')}
                                </DropdownMenuItem>
                                <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[5px] text-xs font-bold" onClick={() => handleUpdateStatus(inst)}>
                                  <RefreshCw className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('checkConnection', 'Force Status Link')}
                                </DropdownMenuItem>
                                <div className="h-px bg-slate-50 my-1" />
                                <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[5px] text-xs font-bold" onClick={() => { setCurrentInstance(inst); setFormData({ ...formData, name: inst.name, instance_id: inst.instance_id, access_token: inst.access_token }); setIsEditModalOpen(true); }}>
                                  <Edit className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('edit', 'Modify Credentials')}
                                </DropdownMenuItem>
                                <DropdownMenuItem className="cursor-pointer py-2 px-3 rounded-[5px] text-xs font-bold" onClick={() => handleMe(inst)}>
                                  <User className="mr-2.5 h-3.5 w-3.5 text-slate-500" /> {t('aboutData', 'Inspect Session Data')}
                                </DropdownMenuItem>
                                <div className="h-px bg-slate-50 my-1" />
                                <DropdownMenuItem className="text-rose-600 focus:bg-rose-50 focus:text-rose-700 cursor-pointer py-2 px-3 rounded-[5px] text-xs font-bold" onClick={() => handleDeleteInstance(inst.id)}>
                                  <Trash2 className="mr-2.5 h-3.5 w-3.5" /> {t('delete', 'Disconnect Instance')}
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
        </SettingCard>

        {/* Feature Routing Card */}
        <SettingCard className="p-0 overflow-hidden">
          <ModernCardHeader
            icon={RefreshCw}
            title={t('chooseWaSender', 'Feature Routing & Mappings')}
            description={t('chooseWaSenderDesc', 'Define which connected number handles each automated flow.')}
          />
          <div className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-7 animate-in slide-in-from-bottom-2 duration-500">

              {features.notifications && (
                <>
                  <div className="space-y-4">
                    <div className="space-y-1">
                      <Label className="text-sm font-bold text-slate-800 flex items-center gap-2">
                        {t('notifUser', 'Users WhatsApp Notifications')}
                        <Badge className="bg-emerald-50 text-emerald-600 border-none text-[9px] font-bold px-1.5 py-0.5 rounded-[3px]">Customer Flow</Badge>
                      </Label>
                      <p className="text-[11px] text-slate-400 font-medium leading-relaxed">{t('notifUserDesc', 'Choose numbers for sending notifications to USERS/Customers.')}</p>
                    </div>
                    <MultiSelectTagify
                      options={instances.map(inst => ({ label: `${inst.name} (${inst.instance_id})`, value: String(inst.id) }))}
                      selected={mappings.notif_user}
                      onChange={(selected) => updateMappings('notif_user', selected)}
                      placeholder="Select senders..."
                      className="rounded-[5px] border-slate-200 bg-white"
                    />
                    <div className="pt-1">
                      <StatusMessage
                        type={mappings.notif_user.length > 0 ? 'active' : 'error'}
                        message={mappings.notif_user.length > 0 
                          ? `<b>${mappings.notif_user.length}</b> instance(s) will handle customer notifications. Multi-sender routing ensures high delivery rates.` 
                          : "Critical: No senders selected for customer notifications. High risk of delivery failure."}
                      />
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div className="space-y-1">
                      <Label className="text-sm font-bold text-slate-800 flex items-center gap-2">
                        {t('notifAdmin', 'Admins WhatsApp Notifications')}
                        <Badge className="bg-blue-50 text-blue-600 border-none text-[9px] font-bold px-1.5 py-0.5 rounded-[3px]">System Flow</Badge>
                      </Label>
                      <p className="text-[11px] text-slate-400 font-medium leading-relaxed">{t('notifAdminDesc', 'Choose numbers for sending notification events to SITE ADMINS.')}</p>
                    </div>
                    <MultiSelectTagify
                      options={instances.map(inst => ({ label: `${inst.name} (${inst.instance_id})`, value: String(inst.id) }))}
                      selected={mappings.notif_admin}
                      onChange={(selected) => updateMappings('notif_admin', selected)}
                      placeholder="Select senders..."
                      className="rounded-[5px] border-slate-200 bg-white"
                    />
                    <div className="pt-1">
                      <StatusMessage
                        type={mappings.notif_admin.length > 0 ? 'active' : 'error'}
                        message={mappings.notif_admin.length > 0 
                          ? `<b>${mappings.notif_admin.length}</b> instance(s) will handle system alerts. Ensuring admins stay informed about site events.` 
                          : "Warning: No senders selected for admin notifications. You might miss important system alerts."}
                      />
                    </div>
                  </div>
                </>
              )}

              <div className="space-y-6 md:col-span-2 border-t border-slate-100 mt-2">
                <h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">Primary Transactional Flows</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-6">
                  {features.otp_login && (
                    <div className="space-y-4">
                      <div className="space-y-1">
                        <Label className="text-xs font-bold text-slate-700 uppercase tracking-wide pl-1">{t('loginWa', 'OTP Login')}</Label>
                        <p className="text-[10px] text-slate-400 font-medium leading-relaxed pl-1">Verification delivery for existing accounts.</p>
                      </div>
                      <MultiSelectTagify
                        options={instances.map((inst: InstanceData) => ({ label: `${inst.name} (${inst.instance_id})`, value: String(inst.id) }))}
                        selected={mappings.login}
                        onChange={(selected) => updateMappings('login', selected)}
                        placeholder="Select senders..."
                        className="rounded-[5px] border-slate-200 bg-white"
                      />
                      <div className="pt-1">
                        <StatusMessage
                          type={mappings.login.length > 0 ? 'active' : 'inactive'}
                          message={mappings.login.length > 0 
                            ? "Secure OTP delivery is active for existing user accounts." 
                            : "Login routing is disabled. Users will fallback to default methods."}
                        />
                      </div>
                    </div>
                  )}

                  {features.otp_signup && (
                    <div className="space-y-4">
                      <div className="space-y-1">
                        <Label className="text-xs font-bold text-slate-700 uppercase tracking-wide pl-1">{t('signupOtp', 'New User Verify')}</Label>
                        <p className="text-[10px] text-slate-400 font-medium leading-relaxed pl-1">Authentication for new registration attempts.</p>
                      </div>
                      <MultiSelectTagify
                        options={instances.map((inst: InstanceData) => ({ label: `${inst.name} (${inst.instance_id})`, value: String(inst.id) }))}
                        selected={mappings.signup}
                        onChange={(selected) => updateMappings('signup', selected)}
                        placeholder="Select senders..."
                        className="rounded-[5px] border-slate-200 bg-white"
                      />
                      <div className="pt-1">
                        <StatusMessage
                          type={mappings.signup.length > 0 ? 'active' : 'inactive'}
                          message={mappings.signup.length > 0 
                            ? "New user verification is active. Ensuring only valid numbers can register." 
                            : "Registration routing is disabled. OTP will not be sent to new users via WhatsApp."}
                        />
                      </div>
                    </div>
                  )}

                  {features.otp_checkout && (
                    <div className="space-y-4">
                      <div className="space-y-1">
                        <Label className="text-xs font-bold text-slate-700 uppercase tracking-wide pl-1">{t('wawpCheckout', 'Checkout Confirmation')}</Label>
                        <p className="text-[10px] text-slate-400 font-medium leading-relaxed pl-1">Order validation and checkout verification.</p>
                      </div>
                      <MultiSelectTagify
                        options={instances.map((inst: InstanceData) => ({ label: `${inst.name} (${inst.instance_id})`, value: String(inst.id) }))}
                        selected={mappings.checkout}
                        onChange={(selected) => updateMappings('checkout', selected)}
                        placeholder="Select senders..."
                        className="rounded-[5px] border-slate-200 bg-white"
                      />
                      <div className="pt-1">
                        <StatusMessage
                          type={mappings.checkout.length > 0 ? 'active' : 'inactive'}
                          message={mappings.checkout.length > 0 
                            ? "WooCommerce checkout verification is active for high-security orders." 
                            : "Checkout verification is currently inactive for this channel."}
                        />
                      </div>
                    </div>
                  )}

                  <div className="space-y-4">
                    <div className="space-y-1">
                      <Label className="text-xs font-bold text-slate-700 uppercase tracking-wide pl-1">General System Sender</Label>
                      <p className="text-[10px] text-slate-400 font-medium leading-relaxed pl-1">Used for system operations, direct messages, and general automation tasks.</p>
                    </div>
                    <MultiSelectTagify
                      options={instances.map((inst: InstanceData) => ({ label: `${inst.name} (${inst.instance_id})`, value: String(inst.id) }))}
                      selected={mappings.general}
                      onChange={(selected) => updateMappings('general', selected)}
                      placeholder="Select senders..."
                      className="rounded-[5px] border-slate-200 bg-white"
                    />
                    <div className="pt-1">
                      <StatusMessage
                        type={mappings.general.length > 0 ? 'active' : 'inactive'}
                        message={mappings.general.length > 0 
                          ? "System sender is active for general automation and background tasks." 
                          : "No general sender selected. Some automated background tasks might fail."}
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </SettingCard>

        {/* Modals */}
        <Sheet open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
          <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="flex-1 overflow-y-auto">
              <ModernCardHeader
                title={t('edit', 'Update Credentials')}
                description="Update your WhatsApp instance API credentials."
                icon={PenBox}
              />
              <div className="p-6 md:p-8 space-y-8">
                <div className="space-y-5">
                  <SettingInput
                    label={t('name', 'Name')}
                    value={formData.name}
                    onChange={(val: string) => setFormData({ ...formData, name: val })}
                    placeholder=""
                    icon={Type}
                  />
                  <SettingInput
                    label={t('instanceId', 'Instance ID')}
                    value={formData.instance_id}
                    onChange={(val: string) => setFormData({ ...formData, instance_id: val })}
                    placeholder=""
                    icon={Hash}
                  />
                  <SettingInput
                    label={t('accessToken', 'Access Token')}
                    value={formData.access_token}
                    onChange={(val: string) => setFormData({ ...formData, access_token: val })}
                    placeholder=""
                    icon={Key}
                    type="password"
                  />
                </div>
              </div>
            </div>

            <div className="p-6 bg-slate-50 border-t border-slate-100 flex gap-3">
              <SecondaryButton onClick={() => setIsEditModalOpen(false)} disabled={isUpdating}>
                {t('close', 'Close')}
              </SecondaryButton>
              <AdminButton onClick={handleEditInstance} loading={isUpdating} icon={RefreshCw} className="flex-[2]">
                {t('save', 'Update Config')}
              </AdminButton>
            </div>
          </SheetContent>
        </Sheet>

        <Dialog open={isTestSuccessModalOpen} onOpenChange={setIsTestSuccessModalOpen}>
          <DialogContent className="sm:max-w-[425px] rounded-[20px] p-0 overflow-hidden border-none shadow-2xl font-sans">
            <DialogTitle className="sr-only">Test Delivery Success</DialogTitle>
            <DialogDescription className="sr-only">Your test WhatsApp message has been sent successfully.</DialogDescription>

            <div className="bg-emerald-500 py-12 flex flex-col items-center justify-center text-white relative overflow-hidden">
              <div className="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2 blur-2xl" />
              <div className="absolute bottom-0 left-0 w-24 h-24 bg-black/5 rounded-full translate-y-1/2 -translate-x-1/2 blur-xl" />
              <div className="w-20 h-20 bg-white/20 rounded-full flex items-center justify-center animate-checkmark">
                <CheckCircle2 className="w-10 h-10 text-white" />
              </div>
              <h3 className="text-3xl font-black uppercase tracking-widest mt-3 text-white leading-none">DONE</h3>
            </div>
            <div className="p-8 pt-6 space-y-6 text-center">
              <div className="space-y-1.5">
                <p className="text-xl font-bold text-slate-900 leading-tight">Check your phone now!</p>
                <p className="text-sm text-slate-500 font-medium">Test delivery sent successfully to <span className="text-emerald-600 font-bold">447441429009</span></p>
              </div>

              <div className="pt-2">
                <AdminButton
                  className="w-full py-7 text-base rounded-2xl shadow-lg bg-[#004242] hover:bg-[#003333] transition-all border-none scale-100 hover:scale-[1.02] active:scale-95"
                  onClick={() => window.open(`https://wa.me/447441429009`, '_blank')}
                >
                  <Smartphone className="w-5 h-5 mr-3" /> Open WhatsApp to Preview
                </AdminButton>
              </div>

              <GhostButton className="w-full text-slate-400 hover:text-slate-600 font-bold" onClick={() => setIsTestSuccessModalOpen(false)}>
                Close
              </GhostButton>
            </div>
          </DialogContent>
        </Dialog>

        <Dialog open={isMeModalOpen} onOpenChange={setIsMeModalOpen}>
          <DialogContent className="sm:max-w-[600px] max-h-[85vh] overflow-hidden flex flex-col rounded-[15px] p-0 border-none shadow-2xl">
            <DialogTitle className="sr-only">Remote Account Details</DialogTitle>
            <DialogDescription className="sr-only">Live session and account metadata from the global API.</DialogDescription>
            <ModernCardHeader
              title={t('aboutData', 'Remote Account Details')}
              description="Live session and account metadata from the global API."
              icon={User}
            />
            <div className="p-6 flex-1 overflow-hidden flex flex-col">
              <div className="flex-1 overflow-auto bg-slate-900 p-5 rounded-xl border border-slate-800 text-emerald-400 font-mono text-[11px] leading-relaxed custom-scrollbar">
                <pre>
                  {JSON.stringify(meData, null, 2)}
                </pre>
              </div>
            </div>
            <div className="p-4 bg-slate-50 border-t border-slate-100 flex justify-end">
              <AdminButton onClick={() => setIsMeModalOpen(false)}>Close Metadata Inspector</AdminButton>
            </div>
          </DialogContent>
        </Dialog>

      </div>
    </SettingsLayout>
  );
}
