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, BookOpen } from 'lucide-react';
import {
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SecondaryButton,
  GhostButton,
  ModernCardHeader,
  SettingCard,
  SettingInput,
  StatusMessage,
  SaveWithStatus,
  SaveFooter
} 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 = useCallback((key: string, fallback: string): string => {
    const val = (dashboardData?.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  }, [dashboardData.i18n]);

  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[],
    general: [] as string[],
    notif_user: [] as string[],
    notif_admin: [] as string[],
  });
  const [features, setFeatures] = useState({
    otp_login: true,
    otp_signup: true,
    notifications: true,
  });
  const fetchInstances = useCallback(async () => {
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web?_=${Date.now()}`, {
        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 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)] : []),
      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),
    });
  }, [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}?_=${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_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(t('addingInstanceToast', 'Adding instance...'));
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web?_=${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(t('instanceAddedToast', '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 || t('failedAddInstanceToast', 'Failed to add instance'), { id: loadingToast });
      }
    } catch {
      toast.error(t('errorOccurredToast', 'An error occurred'), { id: loadingToast });
    } finally {
      setIsAdding(false);
    }
  };

  const handleEditInstance = async () => {
    if (!currentInstance || isUpdating) return;
    setIsUpdating(true);
    const loadingToast = toast.loading(t('updatingInstanceToast', 'Updating instance...'));
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web?_=${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(t('instanceUpdatedToast', '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 || t('failedUpdateInstanceToast', 'Failed to update instance'), { id: loadingToast });
      }
    } catch {
      toast.error(t('errorOccurredToast', 'An error occurred'), { id: loadingToast });
    } finally {
      setIsUpdating(false);
    }
  };

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

  const handleUpdateStatus = useCallback(async (inst: InstanceData) => {
    const loadingToast = toast.loading(t('refreshingInstanceStatusToast', 'Refreshing instance status...'));
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web/ops?_=${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(t('statusUpdatedToast', 'Status updated'), { id: loadingToast });
        fetchInstances();
      } else {
        toast.error(result.message || t('failedCheckStatusToast', 'Failed to check status'), { id: loadingToast });
      }
    } catch {
      toast.error(t('errorOccurredToast', 'An error occurred'), { id: loadingToast });
    }
  }, [dashboardData, fetchInstances, t]);

  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(t('sendingTestDeliveryToast', 'Sending secure test delivery...'));
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/whatsapp_web/ops?_=${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(t('testMessageSentToast', 'Test message sent'), { id: loadingToast });
        setIsTestSuccessModalOpen(true);
      } else {
        toast.error(result.message || t('failedSendTestToast', 'Failed to send test message'), { id: loadingToast });
      }
    } catch {
      toast.error(t('errorOccurredToast', 'An error occurred'), { id: loadingToast });
    }
  }, [dashboardData, t]);

  const handleMe = useCallback(async (inst: InstanceData) => {
    const loadingToast = toast.loading(t('fetchingAccountDataToast', '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(t('dataFetchedToast', 'Data fetched successfully'), { id: loadingToast });
      } else {
        toast.error(result.message || t('failedFetchDataToast', 'Failed to fetch data.'), { id: loadingToast });
      }
    } catch {
      toast.error(t('errorFetchDataToast', 'An error occurred while fetching data.'), { id: loadingToast });
    }
  }, [dashboardData, t]);

  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' || st === 'scan_qr_code' ? t('scanQrCode', 'Scan QR Code') : t(st, 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"
        >
          <div className="flex items-center gap-2.5">
            <SaveWithStatus
              saveStatus={saveStatus}
              hasUnsavedChanges={hasUnsavedChanges}
              isSaving={isSavingMappings}
              onSave={() => handleSave(false)}
            />
            <SecondaryButton
              size="icon"
              className="bg-white border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/dbtn shrink-0"
              onClick={() => window.open(`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-connect-whatsapp-web`, '_blank')}
              title={dashboardData?.rtl ? 'دليل ربط واتساب ويب' : 'WhatsApp Web Guide'}
            >
              <BookOpen className="w-4 h-4 text-slate-500 group-hover/dbtn:text-[#004449] transition-colors" strokeWidth={2} />
            </SecondaryButton>
          </div>
        </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')}
            description={
              <span className="uppercase tracking-wider">
                {t('waWebSlotsDesc', 'Connect and manage your WhatsApp Web instances for automated notifications.')}
              </span>
            }
            rightAction={
              <div className="flex items-center gap-2">
                <Sheet open={isAddModalOpen} onOpenChange={setIsAddModalOpen}>
                  <DialogTrigger asChild>
                    <SecondaryButton onClick={() => setIsAddModalOpen(true)} icon={Plus}>
                      {t('addNewInstance', 'Add New Instance')}
                    </SecondaryButton>
                  </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={t('connectPhoneSuffix', 'Add credentials manually.')}
                        iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/whatsapp.svg`}
                      />
                      <div className="p-6 md:p-8 space-y-8">
                        <div className="space-y-6">
                          <div className="space-y-5">
                            <SettingInput
                              label={t('friendlyName', '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>
            }
          />
          <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">{t('securityToken', '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 text-center">{t('name', 'Name')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest text-center">{t('instanceId', 'Instance ID')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest text-center">{t('accessToken', 'Access Token')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest text-center">{t('status', 'Status')}</TableHead>
                    <TableHead className="font-bold text-slate-500 text-[10px] uppercase tracking-widest text-center 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">{t('connectFirstWa', '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 text-center">{inst.name}</TableCell>
                        <TableCell className="font-mono text-[12px] text-slate-500 text-center">{inst.instance_id}</TableCell>
                        <TableCell className="font-mono text-[12px] text-slate-400 opacity-60 text-center">••••••••{inst.access_token?.slice(-4)}</TableCell>
                        <TableCell className="text-center"><div className="flex justify-center">{getStatusBadge(inst.status, inst.message)}</div></TableCell>
                        <TableCell className="text-center pr-6">
                          <div className="flex items-center justify-center gap-1">
                            <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]">{t('customerFlow', '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={t('selectSendersPlaceholder', '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 
                          ? t('customerNotifActiveMessage', '<b>{count}</b> instance(s) will handle customer notifications. Multi-sender routing ensures high delivery rates.').replace('{count}', String(mappings.notif_user.length))
                          : t('customerNotifInactiveMessage', '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]">{t('systemFlow', '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={t('selectSendersPlaceholder', '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 
                          ? t('adminNotifActiveMessage', '<b>{count}</b> instance(s) will handle system alerts. Ensuring admins stay informed about site events.').replace('{count}', String(mappings.notif_admin.length))
                          : t('adminNotifInactiveMessage', '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">{t('primaryTransactionalFlows', '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-sm font-bold text-slate-800 flex items-center gap-2">{t('loginWa', 'OTP Login')}</Label>
                        <p className="text-[11px] text-slate-400 font-medium leading-relaxed">{t('verificationDeliveryDesc', '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={t('selectSendersPlaceholder', '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 
                            ? t('loginOtpActiveMessage', 'Secure OTP delivery is active for existing user accounts.') 
                            : t('loginOtpInactiveMessage', '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-sm font-bold text-slate-800 flex items-center gap-2">{t('signupOtp', 'New User Verify')}</Label>
                        <p className="text-[11px] text-slate-400 font-medium leading-relaxed">{t('newRegistrationDesc', '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={t('selectSendersPlaceholder', '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 
                            ? t('signupOtpActiveMessage', 'New user verification is active. Ensuring only valid numbers can register.') 
                            : t('signupOtpInactiveMessage', 'Registration routing is disabled. OTP will not be sent to new users via WhatsApp.')}
                        />
                      </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('generalSystemSender', 'General System Sender')}</Label>
                      <p className="text-[11px] text-slate-400 font-medium leading-relaxed">{t('generalSystemSenderDesc', '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={t('selectSendersPlaceholder', '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 
                          ? t('generalActiveMessage', 'System sender is active for general automation and background tasks.') 
                          : t('generalInactiveMessage', '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('updateCredentials', 'Update Credentials')}
                description={t('updateCredentialsDesc', '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('updateConfigBtn', 'Update Config')}
              </AdminButton>
            </div>
          </SheetContent>
        </Sheet>

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

            <div className="flex flex-col items-center justify-center text-center space-y-6">
              {/* Perfect Setup Wizard Success Icon */}
              <div className="w-20 h-20 bg-emerald-50/50 rounded-[1.8rem] flex items-center justify-center border border-emerald-100/50 relative overflow-hidden shadow-sm">
                <div className="absolute inset-0 bg-gradient-to-tr from-emerald-500/10 to-teal-500/10 opacity-50" />
                <div className="absolute inset-0 rounded-[1.8rem] border border-dashed border-emerald-500/30 animate-[spin_40s_linear_infinite]" />
                <div className="absolute w-14 h-14 bg-white rounded-2xl flex items-center justify-center shadow-sm">
                  <CheckCircle2 className="w-8 h-8 text-emerald-600 animate-[pulse_2s_ease-in-out_infinite]" />
                </div>
              </div>

              <div className="space-y-2">
                <h3 className="text-2xl font-extrabold text-[#004449] tracking-wider leading-none">
                  {t('done', 'DONE')}
                </h3>
                <p className="text-xl font-bold text-slate-900 leading-tight">{t('checkPhoneNow', 'Check your phone now!')}</p>
                <p className="text-sm text-slate-500 font-medium">
                  {t('testDeliverySentTo', 'Test delivery sent successfully to')}{' '}
                  <span className="text-emerald-600 font-extrabold bg-emerald-50 px-2.5 py-0.5 rounded-lg border border-emerald-100/50 inline-block font-mono">
                    447441429009
                  </span>
                </p>
              </div>

              <div className="pt-2 w-full">
                <AdminButton
                  className="w-full py-7 text-base rounded-2xl shadow-lg bg-[#004449] 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 rtl:ml-3 rtl:mr-0" /> {t('openWaPreview', 'Open WhatsApp to Preview')}
                </AdminButton>
              </div>

              <GhostButton className="w-full text-slate-400 hover:text-slate-600 font-bold" onClick={() => setIsTestSuccessModalOpen(false)}>
                {t('close', '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">{t('remoteAccountDetails', 'Remote Account Details')}</DialogTitle>
            <DialogDescription className="sr-only">{t('remoteAccountDetailsDesc', 'Live session and account metadata from the global API.')}</DialogDescription>
            <ModernCardHeader
              title={t('remoteAccountDetails', 'Remote Account Details')}
              description={t('remoteAccountDetailsDesc', '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)}>{t('closeMetadataInspector', 'Close Metadata Inspector')}</AdminButton>
            </div>
          </DialogContent>
        </Dialog>

      </div>

      <SaveFooter
        saveStatus={saveStatus}
        hasUnsavedChanges={hasUnsavedChanges}
        isSaving={isSavingMappings}
        onSave={() => handleSave(false)}
        docsUrl={`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-connect-whatsapp-web`}
        docsTitle={dashboardData?.rtl ? "كيفية ربط واتساب ويب" : "How to Connect WhatsApp Web"}
      />
    </SettingsLayout>
  );
}
