'use client';

import { Fragment, useEffect, useMemo, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';

type Employee = {
  id: string;
  name?: string;
  fullName?: string;
  employeeName?: string;
  arabicName?: string;
};

type Device = {
  id: string;
  device_id: string;
  device_name: string;
  brand: string | null;
  model: string | null;
  serial_number: string;
  ip_address: string;
  port: number;
  communication_key: string | null;
  branch_id: string | null;
  timezone: string;
  provider_type: string;
  sync_mode: 'push' | 'pull';
  status: 'active' | 'inactive' | 'maintenance' | 'offline';
  last_sync_at: string | null;
  firmware_version: string | null;
};

type Enrollment = {
  id: string;
  employee_id: string;
  employee_name?: string | null;
  device_id: string;
  device_name?: string | null;
  biometric_user_id: string;
  card_number: string | null;
  enrollment_status: 'active' | 'pending' | 'suspended' | 'revoked';
  enrolled_at: string | null;
  provider_type?: string;
};

type DeviceLog = {
  id: string;
  device_id: string;
  device_name?: string | null;
  employee_id: string | null;
  employee_name?: string | null;
  log_time: string;
  source_type: string;
  punch_type: string | null;
  sync_status: 'pending' | 'processed' | 'failed' | 'duplicate' | 'retried';
  is_duplicate: boolean;
  manual_adjustment: boolean;
  retry_count: number;
};

type DevicesResponse = { items: Device[] };
type EnrollmentResponse = { items: Enrollment[]; employees: Employee[]; devices: Device[] };
type LogsResponse = { items: DeviceLog[]; devices: Device[] };

type BiometricHealthSummary = {
  totalDevices: number;
  offlineDevices: number;
  activeDevices: number;
  staleSyncDevices: number;
  totalLogs: number;
  failedSyncLogs: number;
  duplicateLogs: number;
  retriedLogs: number;
  pendingLogs: number;
};

type BiometricDevicesManagerProps = {
  initialTab?: 'devices' | 'enrollment' | 'logs';
  hideTabs?: boolean;
  locale?: string;
};

function employeeDisplayName(employee: Employee) {
  return employee.name || employee.fullName || employee.employeeName || employee.arabicName || employee.id;
}

export default function BiometricDevicesManager({ initialTab = 'devices', hideTabs = false, locale = 'ar' }: BiometricDevicesManagerProps) {
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState<'devices' | 'enrollment' | 'logs' | 'guide'>(initialTab);
  const isArabic = locale === 'ar';

  const [loadingDevices, setLoadingDevices] = useState(false);
  const [loadingEnrollment, setLoadingEnrollment] = useState(false);
  const [loadingLogs, setLoadingLogs] = useState(false);

  const [devices, setDevices] = useState<Device[]>([]);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [enrollments, setEnrollments] = useState<Enrollment[]>([]);
  const [logs, setLogs] = useState<DeviceLog[]>([]);
  const [healthSummary, setHealthSummary] = useState<BiometricHealthSummary | null>(null);

  const [searchDevices, setSearchDevices] = useState('');
  const [searchEnrollment, setSearchEnrollment] = useState('');
  const [searchLogs, setSearchLogs] = useState('');

  const [deviceForm, setDeviceForm] = useState({
    deviceId: '',
    deviceName: '',
    brand: '',
    model: '',
    serialNumber: '',
    ipAddress: '',
    port: '4370',
    communicationKey: '',
    branchId: '',
    timezone: 'Asia/Riyadh',
    providerType: 'zkteco',
    syncMode: 'pull',
    status: 'active',
    firmwareVersion: '',
  });

  const [enrollmentForm, setEnrollmentForm] = useState({
    employeeId: '',
    deviceId: '',
    biometricUserId: '',
    cardNumber: '',
    enrollmentStatus: 'active',
    enrolledAt: '',
  });

  const [logForm, setLogForm] = useState({
    deviceId: '',
    employeeId: '',
    logTime: '',
    sourceType: 'sdk_pull',
    punchType: 'check_in',
    syncStatus: 'pending',
    duplicateKey: '',
    manualAdjustmentReason: '',
    rawPayload: '{"event":"punch"}',
  });

  const fieldGuide = {
    devices: [
      {
        field: 'deviceId',
        usageAr: '🔧 إدخال يدوي: معرف داخلي ثابت للجهاز داخل ERP (يمكنك اختياره)',
        reasonAr: 'يوفر ربطًا موحدًا بين الأجهزة والسجلات والـ enrollment.',
        usageEn: '🔧 Manual Entry: Stable internal identifier for the device in ERP.',
        reasonEn: 'Provides consistent linking between devices, logs, and enrollments.',
      },
      {
        field: 'deviceName + brand + model',
        usageAr: '📋 إدخال يدوي: اسم وصف الجهاز والعلامة التجارية والموديل (معلومات تنظيمية)',
        reasonAr: 'تنظيم وتصنيف الأجهزة لتسهيل الإدارة والتعريف.',
        usageEn: '📋 Manual Entry: Device description, brand, and model (organizational info).',
        reasonEn: 'Organizes and categorizes devices for easy management.',
      },
      {
        field: 'serialNumber',
        usageAr: '🖥️ من الجهاز: الرقم التسلسلي من الشركة المصنعة (موجود على الجهاز)',
        reasonAr: 'هوية جهاز فريدة موثوقة للتتبع الدقيق.',
        usageEn: '🖥️ From Device: Actual manufacturer serial number (on device label).',
        reasonEn: 'Unique reliable hardware identity for precise tracking.',
      },
      {
        field: 'ipAddress + port',
        usageAr: '🔗 إدخال يدوي: عنوان IP وميناء الاتصال (بيانات الشبكة للجهاز)',
        reasonAr: 'أساس الربط التقني عبر TCP/IP والمزامنة pull/push.',
        usageEn: '🔗 Manual Entry: IP address and port (network configuration).',
        reasonEn: 'Technical foundation for TCP/IP connectivity and sync.',
      },
      {
        field: 'communicationKey',
        usageAr: '🔑 من الجهاز أو يدوي: مفتاح المصادقة الخاص بالجهاز (من وثائق الجهاز)',
        reasonAr: 'حماية الربط الآمن ومنع مزامنة غير مصرح بها.',
        usageEn: '🔑 From Device or Manual: Authentication key (from device documentation).',
        reasonEn: 'Secures sync and prevents unauthorized access.',
      },
      {
        field: 'timezone',
        usageAr: '⏰ تلقائي: المنطقة الزمنية (يُعيّن بشكل افتراضي Asia/Riyadh)',
        reasonAr: 'مزامنة أوقات البصمات بشكل دقيق مع المناطق الجغرافية.',
        usageEn: '⏰ Automatic: Timezone (defaults to Asia/Riyadh).',
        reasonEn: 'Ensures accurate time synchronization for punch records.',
      },
      {
        field: 'providerType + syncMode',
        usageAr: '📱 إدخال يدوي: نوع المزود والمزامنة (اختر من ZKTeco, Suprema, Hikvision..)',
        reasonAr: 'يدعم التوسع لمزودات متعددة ومرنة حسب الجهاز المتوفر.',
        usageEn: '📱 Manual Entry: Select device provider and sync mode (push/pull).',
        reasonEn: 'Enables scalable multi-provider integrations.',
      },
      {
        field: 'status',
        usageAr: '✅ تلقائي: الحالة (يُعيّن افتراضياً \"نشط\", يمكن تعديله لاحقاً)',
        reasonAr: 'مراقبة صحة الجهاز التشغيلية والتنبيه المبكر.',
        usageEn: '✅ Automatic: Status (defaults to \"active\", changeable later).',
        reasonEn: 'Operational health tracking and monitoring.',
      },
    ],
    enrollment: [
      {
        field: 'employeeId',
        usageAr: '👤 من التطبيق: اختر الموظف من القائمة (بيانات من نظام HR)',
        reasonAr: 'ربط البصمة الحيوية بموظف معروف في النظام.',
        usageEn: '👤 From Application: Select employee from list (from HR system).',
        reasonEn: 'Links biometric to a known employee in the system.',
      },
      {
        field: 'deviceId',
        usageAr: '🖥️ من التطبيق: اختر الجهاز من القائمة (من الأجهزة المسجلة)',
        reasonAr: 'يدعم التسجيل على أجهزة متعددة وفروع مختلفة.',
        usageEn: '🖥️ From Application: Select device from list (registered devices).',
        reasonEn: 'Supports multi-device and multi-branch enrollment.',
      },
      {
        field: 'biometricUserId',
        usageAr: '🖥️ من الجهاز: معرف المستخدم كما يراه الجهاز (ضروري للمطابقة)',
        reasonAr: 'يجب أن يطابق معرف المستخدم على جهاز البصمة تماماً.',
        usageEn: '🖥️ From Device: User ID as seen on the device (must match exactly).',
        reasonEn: 'Must match the identifier stored on the biometric device.',
      },
      {
        field: 'cardNumber',
        usageAr: '🎫 اختياري - من الجهاز: رقم البطاقة (إن كان الجهاز يدعم قارئ بطاقات)',
        reasonAr: 'دعم طرق تعريف بديلة مثل البطاقات الممغنطة أو RFID.',
        usageEn: '🎫 Optional - From Device: Card number (if device has card reader).',
        reasonEn: 'Supports alternate ID methods like magnetic cards or RFID.',
      },
      {
        field: 'enrollmentStatus + enrolledAt',
        usageAr: '✅ تلقائي: الحالة والتاريخ (يُعيّن تلقائياً \"نشط\" و التاريخ الحالي)',
        reasonAr: 'إدارة دورة حياة التسجيل بشكل آلي.',
        usageEn: '✅ Automatic: Status and timestamp (set to \"active\" and current date).',
        reasonEn: 'Automatic lifecycle management of enrollment.',
      },
    ],
    logs: [
      {
        field: 'deviceId',
        usageAr: '🖥️ من التطبيق: الجهاز المصدر للبصمة (اختر من القائمة)',
        reasonAr: 'تحديد الجهاز الذي جاءت منه البصمة.',
        usageEn: '🖥️ From Application: Source device (select from list).',
        reasonEn: 'Identifies which device generated the punch.',
      },
      {
        field: 'employeeId',
        usageAr: '👤 اختياري - من التطبيق: الموظف (ستُستخلص تلقائياً من biometricUserId إن أمكن)',
        reasonAr: 'ربط البصمة بموظف معروف، أو يُترك فارغاً للتطابق التلقائي.',
        usageEn: '👤 Optional - From App: Employee (auto-matched from biometricUserId if possible).',
        reasonEn: 'Can be auto-matched; leave empty for automatic linking.',
      },
      {
        field: 'logTime',
        usageAr: '🕐 من الجهاز: وقت البصمة (الوقت الفعلي للدخول/الخروج)',
        reasonAr: 'الوقت الدقيق للحدث من جهاز البصمة.',
        usageEn: '🕐 From Device: Punch timestamp (actual check-in/out time).',
        reasonEn: 'Exact time of the biometric event from device.',
      },
      {
        field: 'sourceType',
        usageAr: '📡 من الجهاز: مصدر الحدث (device/sdk_push/cloud_api/mobile)',
        reasonAr: 'تتبع قناة الاستقبال: جهاز مباشر، SDK، سحابة، أو تطبيق جوال.',
        usageEn: '📡 From Device: Event source (device/SDK/cloud/mobile).',
        reasonEn: 'Tracks which channel delivered the punch (device, SDK, cloud, mobile).',
      },
      {
        field: 'punchType',
        usageAr: '🔔 من الجهاز: نوع الحدث (دخول/خروج/استراحة دخول/استراحة خروج)',
        reasonAr: 'تصنيف نوع البصمة للمعالجة الصحيحة.',
        usageEn: '🔔 From Device: Event type (check_in/check_out/break_in/break_out).',
        reasonEn: 'Classifies punch type for correct processing.',
      },
      {
        field: 'syncStatus',
        usageAr: '⏳ تلقائي: حالة المزامنة (يُعيّن \"pending\" تلقائياً)',
        reasonAr: 'يتحول تلقائياً عند معالجة السجل: pending → processed/failed.',
        usageEn: '⏳ Automatic: Sync status (defaults to \"pending\").',
        reasonEn: 'Auto-updated as record is processed: pending → processed/failed.',
      },
      {
        field: 'duplicateKey',
        usageAr: '🔍 تلقائي: مفتاح الكشف عن التكرار (يُحسب تلقائياً من البيانات)',
        reasonAr: 'يمنع تسجيل نفس البصمة مرتين في نفس الوقت.',
        usageEn: '🔍 Automatic: Duplicate detection key (auto-calculated).',
        reasonEn: 'Prevents duplicate punch entries at same time.',
      },
      {
        field: 'manualAdjustment',
        usageAr: '✏️ إدخال يدوي: سبب التعديل (إذا كان هناك تصحيح يدوي)',
        reasonAr: 'توثيق أي تعديلات يدوية بواسطة HR لأغراض التدقيق.',
        usageEn: '✏️ Manual Entry: Adjustment reason (if manually corrected).',
        reasonEn: 'Documents any HR manual corrections for audit trail.',
      },
      {
        field: 'rawPayload',
        usageAr: '🔬 من الجهاز: بيانات JSON خام من الجهاز (للتدقيق)',
        reasonAr: 'حفظ البيانات الأصلية من الجهاز للتحقق والتحقيق.',
        usageEn: '🔬 From Device: Raw JSON payload (audit trail).',
        reasonEn: 'Preserves original device data for investigation and compliance.',
      },
    ],
  };

  useEffect(() => {
    void fetchDevices();
    void fetchHealthSummary();
  }, []);

  useEffect(() => {
    setActiveTab(initialTab);
  }, [initialTab]);

  useEffect(() => {
    if (activeTab === 'enrollment') {
      void fetchEnrollment();
    }
    if (activeTab === 'logs') {
      void fetchLogs();
      void fetchEnrollment();
    }
  }, [activeTab]);

  const fetchDevices = async () => {
    try {
      setLoadingDevices(true);
      const res = await fetch('/api/hr/attendance/devices?page=1&pageSize=200');
      const payload = (await res.json()) as DevicesResponse;
      if (!res.ok) throw new Error('Failed to fetch devices');
      setDevices(payload.items || []);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر تحميل الأجهزة',
        variant: 'destructive',
      });
    } finally {
      setLoadingDevices(false);
    }
  };

  const fetchHealthSummary = async () => {
    try {
      const res = await fetch('/api/hr/attendance/health/summary');
      const payload = await res.json();
      if (!res.ok) throw new Error(payload?.error || 'Failed to fetch health summary');
      setHealthSummary(payload as BiometricHealthSummary);
    } catch {
      setHealthSummary(null);
    }
  };

  const fetchEnrollment = async () => {
    try {
      setLoadingEnrollment(true);
      const res = await fetch('/api/hr/attendance/enrollment?page=1&pageSize=300');
      const payload = (await res.json()) as EnrollmentResponse;
      if (!res.ok) throw new Error('Failed to fetch enrollment data');
      // Ensure all data is arrays, not single objects
      const items = Array.isArray(payload.items) ? payload.items : [];
      const employees = Array.isArray(payload.employees) ? payload.employees : [];
      const devices = Array.isArray(payload.devices) ? payload.devices : [];
      setEnrollments(items);
      setEmployees(employees);
      setDevices(devices);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر تحميل بيانات التسجيل',
        variant: 'destructive',
      });
    } finally {
      setLoadingEnrollment(false);
    }
  };

  const fetchLogs = async () => {
    try {
      setLoadingLogs(true);
      const res = await fetch('/api/hr/attendance/logs?page=1&pageSize=300');
      const payload = (await res.json()) as LogsResponse;
      if (!res.ok) throw new Error('Failed to fetch logs');
      // Ensure all data is arrays, not single objects
      const items = Array.isArray(payload.items) ? payload.items : [];
      const devices = Array.isArray(payload.devices) ? payload.devices : [];
      setLogs(items);
      setDevices(devices);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر تحميل سجلات الأجهزة',
        variant: 'destructive',
      });
    } finally {
      setLoadingLogs(false);
    }
  };

  const handleCreateDevice = async () => {
    if (!deviceForm.deviceId || !deviceForm.deviceName || !deviceForm.serialNumber || !deviceForm.ipAddress) {
      toast({ title: 'تنبيه', description: 'يرجى تعبئة: deviceId و deviceName و serialNumber و ipAddress', variant: 'destructive' });
      return;
    }

    const res = await fetch('/api/hr/attendance/devices', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...deviceForm,
        port: Number(deviceForm.port || 4370),
        timezone: deviceForm.timezone || 'Asia/Riyadh', // تلقائي
        status: deviceForm.status || 'active', // تلقائي
      }),
    });
    const payload = await res.json();
    if (!res.ok) {
      toast({ title: 'خطأ', description: payload?.error || 'فشل إنشاء الجهاز', variant: 'destructive' });
      return;
    }

    toast({ title: 'تم', description: 'تم تسجيل الجهاز بنجاح' });
    setDeviceForm((prev) => ({ ...prev, deviceId: '', deviceName: '', serialNumber: '', ipAddress: '' }));
    await fetchDevices();
    await fetchHealthSummary();
  };

  const handleDeviceAction = async (id: string, body: Record<string, unknown>) => {
    const res = await fetch(`/api/hr/attendance/devices/${id}/status`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    const payload = await res.json();
    if (!res.ok) {
      toast({ title: 'خطأ', description: payload?.error || 'فشل تحديث الجهاز', variant: 'destructive' });
      return;
    }
    toast({ title: 'تم', description: 'تم تحديث الجهاز' });
    await fetchDevices();
    await fetchHealthSummary();
  };

  const handleCreateEnrollment = async () => {
    if (!enrollmentForm.employeeId || !enrollmentForm.deviceId || !enrollmentForm.biometricUserId) {
      toast({ title: 'تنبيه', description: 'يرجى تعبئة: employeeId, deviceId, biometricUserId (الحقول المطلوبة فقط)', variant: 'destructive' });
      return;
    }

    const res = await fetch('/api/hr/attendance/enrollment', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        employeeId: enrollmentForm.employeeId,
        deviceId: enrollmentForm.deviceId,
        biometricUserId: enrollmentForm.biometricUserId,
        cardNumber: enrollmentForm.cardNumber || undefined,
        enrollmentStatus: enrollmentForm.enrollmentStatus || 'active', // تلقائي
        enrolledAt: enrollmentForm.enrolledAt || new Date().toISOString(), // تلقائي
      }),
    });
    const payload = await res.json();
    if (!res.ok) {
      toast({ title: 'خطأ', description: payload?.error || 'فشل التسجيل على الجهاز', variant: 'destructive' });
      return;
    }

    toast({ title: 'تم', description: 'تم إنشاء Enrollment بنجاح' });
    setEnrollmentForm((prev) => ({ ...prev, biometricUserId: '', cardNumber: '', enrolledAt: '' }));
    await fetchEnrollment();
  };

  const handleEnrollmentStatus = async (id: string, status: Enrollment['enrollment_status']) => {
    const res = await fetch(`/api/hr/attendance/enrollment/${id}/status`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status }),
    });
    const payload = await res.json();
    if (!res.ok) {
      toast({ title: 'خطأ', description: payload?.error || 'فشل تحديث حالة التسجيل', variant: 'destructive' });
      return;
    }

    toast({ title: 'تم', description: 'تم تحديث الحالة' });
    await fetchEnrollment();
  };

  const handleCreateLog = async () => {
    if (!logForm.deviceId || !logForm.logTime) {
      toast({ title: 'تنبيه', description: 'يرجى تحديد: الجهاز ووقت البصمة (الحقول المطلوبة فقط)', variant: 'destructive' });
      return;
    }

    let parsedPayload: Record<string, unknown> | undefined;
    try {
      parsedPayload = logForm.rawPayload ? JSON.parse(logForm.rawPayload) : undefined;
    } catch {
      toast({ title: 'تنبيه', description: 'صيغة raw payload غير صحيحة', variant: 'destructive' });
      return;
    }

    // حساب duplicateKey تلقائياً من البيانات الأساسية
    const duplicateKey = logForm.duplicateKey || `${logForm.deviceId}-${logForm.logTime}`;

    const res = await fetch('/api/hr/attendance/logs', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        deviceId: logForm.deviceId,
        employeeId: logForm.employeeId || undefined,
        logTime: logForm.logTime,
        sourceType: logForm.sourceType || 'device', // تلقائي
        punchType: logForm.punchType || 'check_in', // تلقائي
        syncStatus: 'pending', // تلقائي دائماً
        duplicateKey: duplicateKey,
        manualAdjustment: Boolean(logForm.manualAdjustmentReason),
        manualAdjustmentReason: logForm.manualAdjustmentReason || undefined,
        rawPayload: parsedPayload,
      }),
    });
    const payload = await res.json();
    if (!res.ok) {
      toast({ title: 'خطأ', description: payload?.error || 'فشل إضافة log', variant: 'destructive' });
      return;
    }

    toast({ title: 'تم', description: 'تمت إضافة log خام بنجاح' });
    setLogForm((prev) => ({ ...prev, duplicateKey: '', manualAdjustmentReason: '' }));
    await fetchLogs();
    await fetchHealthSummary();
  };

  const filteredDevices = useMemo(() => {
    const devicesArray = Array.isArray(devices) ? devices : [];
    const q = searchDevices.trim().toLowerCase();
    if (!q) return devicesArray;
    return devicesArray.filter((d) =>
      [d.device_name, d.device_id, d.serial_number, d.ip_address, d.provider_type].some((value) =>
        String(value || '').toLowerCase().includes(q)
      )
    );
  }, [devices, searchDevices]);

  const filteredEnrollment = useMemo(() => {
    const enrollmentsArray = Array.isArray(enrollments) ? enrollments : [];
    const q = searchEnrollment.trim().toLowerCase();
    if (!q) return enrollmentsArray;
    return enrollmentsArray.filter((e) =>
      [e.employee_name, e.device_name, e.biometric_user_id, e.card_number].some((value) =>
        String(value || '').toLowerCase().includes(q)
      )
    );
  }, [enrollments, searchEnrollment]);

  const filteredLogs = useMemo(() => {
    const logsArray = Array.isArray(logs) ? logs : [];
    const q = searchLogs.trim().toLowerCase();
    if (!q) return logsArray;
    return logsArray.filter((log) =>
      [log.device_name, log.employee_name, log.source_type, log.punch_type, log.sync_status].some((value) =>
        String(value || '').toLowerCase().includes(q)
      )
    );
  }, [logs, searchLogs]);

  return (
    <div className='space-y-6'>
      <div>
        <h1 className='text-3xl font-bold'>إدارة نظام البصمة الاحترافي</h1>
        <p className='text-muted-foreground mt-1'>
          Architecture من ثلاث طبقات مستقلة: الأجهزة، التسجيل على الأجهزة، وسجلات البصمة الخام والمعالجة.
        </p>
      </div>

      <div className='grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3'>
        <div className='rounded-md border p-3'>
          <div className='text-xs text-muted-foreground'>إجمالي الأجهزة</div>
          <div className='text-2xl font-bold'>{healthSummary?.totalDevices ?? 0}</div>
        </div>
        <div className='rounded-md border p-3'>
          <div className='text-xs text-muted-foreground'>أجهزة Offline</div>
          <div className='text-2xl font-bold text-red-700'>{healthSummary?.offlineDevices ?? 0}</div>
        </div>
        <div className='rounded-md border p-3'>
          <div className='text-xs text-muted-foreground'>Failed Sync</div>
          <div className='text-2xl font-bold text-amber-700'>{healthSummary?.failedSyncLogs ?? 0}</div>
        </div>
        <div className='rounded-md border p-3'>
          <div className='text-xs text-muted-foreground'>Retry Queue</div>
          <div className='text-2xl font-bold text-blue-700'>{healthSummary?.retriedLogs ?? 0}</div>
        </div>
        <div className='rounded-md border p-3'>
          <div className='text-xs text-muted-foreground'>Pending Logs</div>
          <div className='text-2xl font-bold'>{healthSummary?.pendingLogs ?? 0}</div>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as any)} className='w-full'>
        {!hideTabs ? (
          <TabsList className='mb-4 flex h-auto flex-wrap justify-start gap-1 bg-muted p-1 rounded-lg'>
            <TabsTrigger value='devices'>{isArabic ? '1) الأجهزة' : '1) Devices'}</TabsTrigger>
            <TabsTrigger value='enrollment'>{isArabic ? '2) الربط (Enrollment)' : '2) Enrollment'}</TabsTrigger>
            <TabsTrigger value='logs'>{isArabic ? '3) سجلات الحضور' : '3) Attendance Logs'}</TabsTrigger>
            <TabsTrigger value='guide'>{isArabic ? 'دليل استخدام' : 'Usage Guide'}</TabsTrigger>
          </TabsList>
        ) : null}

        <TabsContent value='devices' className='space-y-4'>
          <Card>
            <CardHeader>
              <CardTitle>إدارة أجهزة البصمة (Devices)</CardTitle>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='grid grid-cols-1 md:grid-cols-4 gap-3'>
                <Input placeholder='deviceId' value={deviceForm.deviceId} onChange={(e) => setDeviceForm((p) => ({ ...p, deviceId: e.target.value }))} />
                <Input placeholder='deviceName' value={deviceForm.deviceName} onChange={(e) => setDeviceForm((p) => ({ ...p, deviceName: e.target.value }))} />
                <Input placeholder='brand' value={deviceForm.brand} onChange={(e) => setDeviceForm((p) => ({ ...p, brand: e.target.value }))} />
                <Input placeholder='model' value={deviceForm.model} onChange={(e) => setDeviceForm((p) => ({ ...p, model: e.target.value }))} />

                <Input placeholder='serialNumber' value={deviceForm.serialNumber} onChange={(e) => setDeviceForm((p) => ({ ...p, serialNumber: e.target.value }))} />
                <Input placeholder='ipAddress' value={deviceForm.ipAddress} onChange={(e) => setDeviceForm((p) => ({ ...p, ipAddress: e.target.value }))} />
                <Input placeholder='port' value={deviceForm.port} onChange={(e) => setDeviceForm((p) => ({ ...p, port: e.target.value }))} />
                <Input placeholder='communicationKey' value={deviceForm.communicationKey} onChange={(e) => setDeviceForm((p) => ({ ...p, communicationKey: e.target.value }))} />

                <Input placeholder='branchId' value={deviceForm.branchId} onChange={(e) => setDeviceForm((p) => ({ ...p, branchId: e.target.value }))} />
                <Input placeholder='timezone' value={deviceForm.timezone} onChange={(e) => setDeviceForm((p) => ({ ...p, timezone: e.target.value }))} />
                <Input placeholder='firmwareVersion' value={deviceForm.firmwareVersion} onChange={(e) => setDeviceForm((p) => ({ ...p, firmwareVersion: e.target.value }))} />

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={deviceForm.providerType} onChange={(e) => setDeviceForm((p) => ({ ...p, providerType: e.target.value }))}>
                  <option value='zkteco'>ZKTeco</option>
                  <option value='suprema'>Suprema</option>
                  <option value='hikvision'>Hikvision</option>
                  <option value='anviz'>Anviz</option>
                  <option value='tcpip'>TCP/IP</option>
                  <option value='cloud_api'>Cloud API</option>
                  <option value='push_sdk'>Push SDK</option>
                </select>

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={deviceForm.syncMode} onChange={(e) => setDeviceForm((p) => ({ ...p, syncMode: e.target.value }))}>
                  <option value='pull'>Pull</option>
                  <option value='push'>Push</option>
                </select>

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={deviceForm.status} onChange={(e) => setDeviceForm((p) => ({ ...p, status: e.target.value }))}>
                  <option value='active'>active</option>
                  <option value='inactive'>inactive</option>
                  <option value='maintenance'>maintenance</option>
                  <option value='offline'>offline</option>
                </select>
              </div>

              <Button onClick={() => void handleCreateDevice()}>تسجيل الجهاز</Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>قائمة الأجهزة</CardTitle>
            </CardHeader>
            <CardContent className='space-y-3'>
              <Input placeholder='بحث بالأجهزة' value={searchDevices} onChange={(e) => setSearchDevices(e.target.value)} className='md:max-w-md' />
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>الجهاز</TableHead>
                    <TableHead>Provider</TableHead>
                    <TableHead>Network</TableHead>
                    <TableHead>Sync</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Last Sync</TableHead>
                    <TableHead>إجراءات</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loadingDevices ? (
                    <TableRow><TableCell colSpan={7} className='text-center py-6 text-muted-foreground'>جاري التحميل...</TableCell></TableRow>
                  ) : !Array.isArray(filteredDevices) || filteredDevices.length === 0 ? (
                    <TableRow><TableCell colSpan={7} className='text-center py-6 text-muted-foreground'>لا توجد أجهزة</TableCell></TableRow>
                  ) : (
                    filteredDevices.map((d) => (
                      <TableRow key={d.id}>
                        <TableCell>
                          <div className='space-y-1'>
                            <div className='font-medium'>{d.device_name}</div>
                            <div className='text-xs text-muted-foreground'>{d.device_id} | {d.serial_number}</div>
                          </div>
                        </TableCell>
                        <TableCell>{d.provider_type}</TableCell>
                        <TableCell>{d.ip_address}:{d.port}</TableCell>
                        <TableCell><Badge variant='outline'>{d.sync_mode.toUpperCase()}</Badge></TableCell>
                        <TableCell>
                          <Badge className={d.status === 'active' ? 'bg-green-100 text-green-800' : d.status === 'offline' ? 'bg-red-100 text-red-800' : 'bg-amber-100 text-amber-800'}>{d.status}</Badge>
                        </TableCell>
                        <TableCell>{d.last_sync_at ? new Date(d.last_sync_at).toLocaleString() : '-'}</TableCell>
                        <TableCell>
                          <div className='flex gap-2'>
                            <Button size='sm' variant='outline' onClick={() => void handleDeviceAction(d.id, { action: 'sync-now' })}>Sync</Button>
                            <Button size='sm' variant='outline' onClick={() => void handleDeviceAction(d.id, { status: d.status === 'active' ? 'inactive' : 'active' })}>{d.status === 'active' ? 'تعطيل' : 'تفعيل'}</Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value='enrollment' className='space-y-4'>
          <Card>
            <CardHeader>
              <CardTitle>Enrollment - ربط الموظف بالجهاز</CardTitle>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='grid grid-cols-1 md:grid-cols-3 gap-3'>
                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={enrollmentForm.employeeId} onChange={(e) => setEnrollmentForm((p) => ({ ...p, employeeId: e.target.value }))}>
                  <option value=''>employeeId</option>
                  {Array.isArray(employees) && employees.map((e) => (<option key={e.id} value={e.id}>{employeeDisplayName(e)}</option>))}
                </select>

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={enrollmentForm.deviceId} onChange={(e) => setEnrollmentForm((p) => ({ ...p, deviceId: e.target.value }))}>
                  <option value=''>deviceId</option>
                  {Array.isArray(devices) && devices.map((d) => (<option key={d.id} value={d.id}>{d.device_name} ({d.device_id})</option>))}
                </select>

                <Input placeholder='biometricUserId' value={enrollmentForm.biometricUserId} onChange={(e) => setEnrollmentForm((p) => ({ ...p, biometricUserId: e.target.value }))} />
                <Input placeholder='cardNumber' value={enrollmentForm.cardNumber} onChange={(e) => setEnrollmentForm((p) => ({ ...p, cardNumber: e.target.value }))} />

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={enrollmentForm.enrollmentStatus} onChange={(e) => setEnrollmentForm((p) => ({ ...p, enrollmentStatus: e.target.value }))}>
                  <option value='active'>active</option>
                  <option value='pending'>pending</option>
                  <option value='suspended'>suspended</option>
                  <option value='revoked'>revoked</option>
                </select>

                <Input type='datetime-local' value={enrollmentForm.enrolledAt} onChange={(e) => setEnrollmentForm((p) => ({ ...p, enrolledAt: e.target.value }))} />
              </div>

              <Button onClick={() => void handleCreateEnrollment()}>إنشاء Enrollment</Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>سجلات Enrollment</CardTitle>
            </CardHeader>
            <CardContent className='space-y-3'>
              <Input placeholder='بحث في enrollment' value={searchEnrollment} onChange={(e) => setSearchEnrollment(e.target.value)} className='md:max-w-md' />
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>الموظف</TableHead>
                    <TableHead>الجهاز</TableHead>
                    <TableHead>Biometric User</TableHead>
                    <TableHead>Card</TableHead>
                    <TableHead>الحالة</TableHead>
                    <TableHead>إجراءات</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loadingEnrollment ? (
                    <TableRow><TableCell colSpan={6} className='text-center py-6 text-muted-foreground'>جاري التحميل...</TableCell></TableRow>
                  ) : !Array.isArray(filteredEnrollment) || filteredEnrollment.length === 0 ? (
                    <TableRow><TableCell colSpan={6} className='text-center py-6 text-muted-foreground'>لا توجد سجلات</TableCell></TableRow>
                  ) : (
                    filteredEnrollment.map((enr) => (
                      <TableRow key={enr.id}>
                        <TableCell>{enr.employee_name || enr.employee_id}</TableCell>
                        <TableCell>{enr.device_name || enr.device_id}</TableCell>
                        <TableCell>{enr.biometric_user_id}</TableCell>
                        <TableCell>{enr.card_number || '-'}</TableCell>
                        <TableCell><Badge variant='outline'>{enr.enrollment_status}</Badge></TableCell>
                        <TableCell>
                          <div className='flex gap-2'>
                            <Button size='sm' variant='outline' onClick={() => void handleEnrollmentStatus(enr.id, 'active')}>تفعيل</Button>
                            <Button size='sm' variant='outline' onClick={() => void handleEnrollmentStatus(enr.id, 'suspended')}>تعليق</Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value='logs' className='space-y-4'>
          <Card>
            <CardHeader>
              <CardTitle>Attendance Logs - سجلات خام ومعالجة</CardTitle>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='grid grid-cols-1 md:grid-cols-3 gap-3'>
                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={logForm.deviceId} onChange={(e) => setLogForm((p) => ({ ...p, deviceId: e.target.value }))}>
                  <option value=''>device source</option>
                  {Array.isArray(devices) && devices.map((d) => (<option key={d.id} value={d.id}>{d.device_name}</option>))}
                </select>

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={logForm.employeeId} onChange={(e) => setLogForm((p) => ({ ...p, employeeId: e.target.value }))}>
                  <option value=''>employeeId (اختياري)</option>
                  {Array.isArray(employees) && employees.map((e) => (<option key={e.id} value={e.id}>{employeeDisplayName(e)}</option>))}
                </select>

                <Input type='datetime-local' value={logForm.logTime} onChange={(e) => setLogForm((p) => ({ ...p, logTime: e.target.value }))} />

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={logForm.sourceType} onChange={(e) => setLogForm((p) => ({ ...p, sourceType: e.target.value }))}>
                  <option value='device'>device</option>
                  <option value='sdk_push'>sdk_push</option>
                  <option value='sdk_pull'>sdk_pull</option>
                  <option value='cloud_api'>cloud_api</option>
                  <option value='mobile'>mobile</option>
                </select>

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={logForm.punchType} onChange={(e) => setLogForm((p) => ({ ...p, punchType: e.target.value }))}>
                  <option value='check_in'>check_in</option>
                  <option value='check_out'>check_out</option>
                  <option value='break_in'>break_in</option>
                  <option value='break_out'>break_out</option>
                  <option value='unknown'>unknown</option>
                </select>

                <select className='w-full h-10 rounded-md border bg-background px-3 text-sm' value={logForm.syncStatus} onChange={(e) => setLogForm((p) => ({ ...p, syncStatus: e.target.value }))}>
                  <option value='pending'>pending</option>
                  <option value='processed'>processed</option>
                  <option value='failed'>failed</option>
                  <option value='duplicate'>duplicate</option>
                  <option value='retried'>retried</option>
                </select>

                <Input placeholder='duplicateKey (for protection)' value={logForm.duplicateKey} onChange={(e) => setLogForm((p) => ({ ...p, duplicateKey: e.target.value }))} />
                <Input placeholder='manual adjustment reason' value={logForm.manualAdjustmentReason} onChange={(e) => setLogForm((p) => ({ ...p, manualAdjustmentReason: e.target.value }))} />
              </div>

              <textarea
                className='w-full min-h-[120px] rounded-md border bg-background p-3 text-sm font-mono'
                value={logForm.rawPayload}
                onChange={(e) => setLogForm((p) => ({ ...p, rawPayload: e.target.value }))}
                placeholder='raw device payload (JSON)'
              />

              <Button onClick={() => void handleCreateLog()}>إضافة Raw Log</Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>سجلات الحضور من الأجهزة</CardTitle>
            </CardHeader>
            <CardContent className='space-y-3'>
              <Input placeholder='بحث في logs' value={searchLogs} onChange={(e) => setSearchLogs(e.target.value)} className='md:max-w-md' />
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>الوقت</TableHead>
                    <TableHead>الجهاز</TableHead>
                    <TableHead>الموظف</TableHead>
                    <TableHead>Punch</TableHead>
                    <TableHead>Sync</TableHead>
                    <TableHead>Flags</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loadingLogs ? (
                    <TableRow><TableCell colSpan={6} className='text-center py-6 text-muted-foreground'>جاري التحميل...</TableCell></TableRow>
                  ) : !Array.isArray(filteredLogs) || filteredLogs.length === 0 ? (
                    <TableRow><TableCell colSpan={6} className='text-center py-6 text-muted-foreground'>لا توجد logs</TableCell></TableRow>
                  ) : (
                    filteredLogs.map((log) => (
                      <TableRow key={log.id}>
                        <TableCell>{new Date(log.log_time).toLocaleString()}</TableCell>
                        <TableCell>{log.device_name || log.device_id}</TableCell>
                        <TableCell>{log.employee_name || log.employee_id || '-'}</TableCell>
                        <TableCell>{log.punch_type || '-'}</TableCell>
                        <TableCell><Badge variant='outline'>{log.sync_status}</Badge></TableCell>
                        <TableCell>
                          <div className='flex gap-2'>
                            {log.is_duplicate ? <Badge className='bg-amber-100 text-amber-800'>duplicate</Badge> : null}
                            {log.manual_adjustment ? <Badge className='bg-blue-100 text-blue-800'>manual</Badge> : null}
                            {log.retry_count > 0 ? <Badge className='bg-red-100 text-red-800'>retry {log.retry_count}</Badge> : null}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value='guide' className='space-y-4'>
          <Card>
            <CardHeader>
              <CardTitle>{isArabic ? 'دليل استخدام الحقول' : 'Field Usage Guide'}</CardTitle>
            </CardHeader>
            <CardContent className='space-y-5'>
              <div>
                <h3 className='font-semibold mb-2'>{isArabic ? '1) Devices' : '1) Devices'}</h3>
                <div className='grid grid-cols-1 md:grid-cols-3 gap-2 text-sm'>
                  <div className='font-medium'>{isArabic ? 'الحقل' : 'Field'}</div>
                  <div className='font-medium'>{isArabic ? 'كيف يستخدم' : 'How to use'}</div>
                  <div className='font-medium'>{isArabic ? 'لماذا يستخدم' : 'Why it matters'}</div>
                  {fieldGuide.devices.map((item) => (
                    <Fragment key={item.field}>
                      <div className='rounded border p-2'>{item.field}</div>
                      <div className='rounded border p-2'>{isArabic ? item.usageAr : item.usageEn}</div>
                      <div className='rounded border p-2'>{isArabic ? item.reasonAr : item.reasonEn}</div>
                    </Fragment>
                  ))}
                </div>
              </div>

              <div>
                <h3 className='font-semibold mb-2'>{isArabic ? '2) Enrollment' : '2) Enrollment'}</h3>
                <div className='grid grid-cols-1 md:grid-cols-3 gap-2 text-sm'>
                  <div className='font-medium'>{isArabic ? 'الحقل' : 'Field'}</div>
                  <div className='font-medium'>{isArabic ? 'كيف يستخدم' : 'How to use'}</div>
                  <div className='font-medium'>{isArabic ? 'لماذا يستخدم' : 'Why it matters'}</div>
                  {fieldGuide.enrollment.map((item) => (
                    <Fragment key={item.field}>
                      <div className='rounded border p-2'>{item.field}</div>
                      <div className='rounded border p-2'>{isArabic ? item.usageAr : item.usageEn}</div>
                      <div className='rounded border p-2'>{isArabic ? item.reasonAr : item.reasonEn}</div>
                    </Fragment>
                  ))}
                </div>
              </div>

              <div>
                <h3 className='font-semibold mb-2'>{isArabic ? '3) Attendance Logs' : '3) Attendance Logs'}</h3>
                <div className='grid grid-cols-1 md:grid-cols-3 gap-2 text-sm'>
                  <div className='font-medium'>{isArabic ? 'الحقل' : 'Field'}</div>
                  <div className='font-medium'>{isArabic ? 'كيف يستخدم' : 'How to use'}</div>
                  <div className='font-medium'>{isArabic ? 'لماذا يستخدم' : 'Why it matters'}</div>
                  {fieldGuide.logs.map((item) => (
                    <Fragment key={item.field}>
                      <div className='rounded border p-2'>{item.field}</div>
                      <div className='rounded border p-2'>{isArabic ? item.usageAr : item.usageEn}</div>
                      <div className='rounded border p-2'>{isArabic ? item.reasonAr : item.reasonEn}</div>
                    </Fragment>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
