'use client';

import { useEffect, useMemo, useState } from 'react';
import type {
  ChartOfAccount,
  ExpenseDocumentHistoryEntry,
  ExpenseDocument,
  ExpensePayment,
  ProductionItem,
  RecurringExpenseTemplate,
} from '@/lib/types';
import { formatDateDDMMYYYY } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/hooks/use-toast';

type Props = {
  expenseItems: ProductionItem[];
  chartAccounts: ChartOfAccount[];
};

type TemplateStatus = 'active' | 'paused' | 'closed';
type Frequency = 'monthly' | 'yearly';
type ApprovalPolicy = 'none' | 'single_step' | 'two_step';
type PaymentMethod = 'cash' | 'bank' | 'credit' | 'mixed';
type DocumentSortKey = 'description' | 'period' | 'amount' | 'paidAmount' | 'status';
type SortDirection = 'asc' | 'desc';

const STATUS_LABELS: Record<string, string> = {
  draft: 'مسودة',
  pending_approval: 'بانتظار الاعتماد',
  approved: 'معتمد',
  rejected: 'مرفوض',
  posted: 'مرحل',
  partially_paid: 'مسدد جزئيا',
  paid: 'مسدد بالكامل',
  cancelled: 'ملغي',
  active: 'نشط',
  paused: 'موقوف',
  closed: 'مغلق',
};

const HISTORY_ACTION_LABELS: Record<string, string> = {
  created: 'إنشاء مستند',
  submitted: 'إرسال للاعتماد',
  approved: 'اعتماد',
  rejected: 'رفض',
  posted: 'ترحيل',
  payment: 'تسجيل دفعة',
  status_changed: 'تغيير حالة',
};

function formatAmount(value: number): string {
  return Number(value || 0).toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

function getStatusLabel(status?: string): string {
  if (!status) return '-';
  return STATUS_LABELS[status] || status;
}

function getHistoryActionLabel(action?: string): string {
  if (!action) return '-';
  return HISTORY_ACTION_LABELS[action] || action;
}

function escapeCsvCell(value: unknown): string {
  const text = String(value ?? '').replace(/"/g, '""');
  return `"${text}"`;
}

function statusBadgeVariant(status: string): 'default' | 'secondary' | 'destructive' | 'outline' {
  if (status === 'paid' || status === 'active' || status === 'posted') return 'default';
  if (status === 'rejected' || status === 'cancelled' || status === 'closed') return 'destructive';
  if (status === 'pending_approval' || status === 'approved' || status === 'partially_paid') return 'secondary';
  return 'outline';
}

export function ExpenseRecurringManager({ expenseItems, chartAccounts }: Props) {
  const { toast } = useToast();

  const expenseAccountOptions = useMemo(
    () => {
      const accounts = Array.isArray(chartAccounts) ? chartAccounts : [];
      return accounts.filter((a) => String(a.code || '').startsWith('5'));
    },
    [chartAccounts]
  );
  const payableAccountOptions = useMemo(
    () => {
      const accounts = Array.isArray(chartAccounts) ? chartAccounts : [];
      return accounts.filter((a) => String(a.code || '').startsWith('21'));
    },
    [chartAccounts]
  );
  const paymentAccountOptions = useMemo(
    () => {
      const accounts = Array.isArray(chartAccounts) ? chartAccounts : [];
      return accounts.filter((a) => String(a.code || '').startsWith('11'));
    },
    [chartAccounts]
  );

  const [templates, setTemplates] = useState<RecurringExpenseTemplate[]>([]);
  const [documents, setDocuments] = useState<ExpenseDocument[]>([]);
  const [payments, setPayments] = useState<ExpensePayment[]>([]);
  const [history, setHistory] = useState<ExpenseDocumentHistoryEntry[]>([]);

  const [loadingTemplates, setLoadingTemplates] = useState(false);
  const [loadingDocuments, setLoadingDocuments] = useState(false);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [loadingHistory, setLoadingHistory] = useState(false);

  const [templateStatusFilter, setTemplateStatusFilter] = useState<TemplateStatus | 'all'>('active');
  const [documentStatusFilter, setDocumentStatusFilter] = useState<string>('all');
  const [historyActionFilter, setHistoryActionFilter] = useState<string>('all');
  const [historyQuery, setHistoryQuery] = useState('');
  const [documentsSortKey, setDocumentsSortKey] = useState<DocumentSortKey>('period');
  const [documentsSortDirection, setDocumentsSortDirection] = useState<SortDirection>('desc');
  const [documentsPage, setDocumentsPage] = useState(1);
  const [documentsPageSize, setDocumentsPageSize] = useState(10);

  const [selectedDocumentId, setSelectedDocumentId] = useState('');

  const [templateName, setTemplateName] = useState('');
  const [templateExpenseItemId, setTemplateExpenseItemId] = useState('');
  const [templateExpenseAccountCode, setTemplateExpenseAccountCode] = useState('');
  const [templatePayableAccountCode, setTemplatePayableAccountCode] = useState('2130');
  const [templateDefaultAmount, setTemplateDefaultAmount] = useState('0');
  const [templateFrequency, setTemplateFrequency] = useState<Frequency>('monthly');
  const [templateIntervalCount, setTemplateIntervalCount] = useState('1');
  const [templateStartDate, setTemplateStartDate] = useState('');
  const [templateDayOfMonth, setTemplateDayOfMonth] = useState('');
  const [templateMonthOfYear, setTemplateMonthOfYear] = useState('');
  const [templateApprovalPolicy, setTemplateApprovalPolicy] = useState<ApprovalPolicy>('single_step');
  const [templateAutoSubmit, setTemplateAutoSubmit] = useState(false);

  const [generateAsOfDate, setGenerateAsOfDate] = useState('');

  const [paymentDate, setPaymentDate] = useState('');
  const [paymentAmount, setPaymentAmount] = useState('');
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('bank');
  const [paymentAccountCode, setPaymentAccountCode] = useState('');
  const [paymentReference, setPaymentReference] = useState('');

  const selectedDocument = useMemo(
    () => {
      const docsArray = Array.isArray(documents) ? documents : [];
      return docsArray.find((d) => d.id === selectedDocumentId) || null;
    },
    [documents, selectedDocumentId]
  );

  const filteredHistory = useMemo(() => {
    const historyArray = Array.isArray(history) ? history : [];
    const q = historyQuery.trim().toLowerCase();
    return historyArray.filter((entry) => {
      if (historyActionFilter !== 'all' && entry.action !== historyActionFilter) return false;
      if (!q) return true;

      const haystack = [
        getHistoryActionLabel(entry.action),
        getStatusLabel(entry.fromStatus || ''),
        getStatusLabel(entry.toStatus),
        entry.actorName || '',
        entry.actorId || '',
        entry.note || '',
      ]
        .join(' ')
        .toLowerCase();

      return haystack.includes(q);
    });
  }, [history, historyActionFilter, historyQuery]);

  const sortedDocuments = useMemo(() => {
    const docsArray = Array.isArray(documents) ? documents : [];
    const copy = [...docsArray];
    copy.sort((a, b) => {
      let result = 0;

      if (documentsSortKey === 'description') {
        result = String(a.description || '').localeCompare(String(b.description || ''), 'ar');
      } else if (documentsSortKey === 'period') {
        const aPeriod = Number(a.periodYear) * 100 + Number(a.periodMonth);
        const bPeriod = Number(b.periodYear) * 100 + Number(b.periodMonth);
        result = aPeriod - bPeriod;
      } else if (documentsSortKey === 'amount') {
        result = Number(a.amount || 0) - Number(b.amount || 0);
      } else if (documentsSortKey === 'paidAmount') {
        result = Number(a.paidAmount || 0) - Number(b.paidAmount || 0);
      } else if (documentsSortKey === 'status') {
        result = String(getStatusLabel(a.status)).localeCompare(String(getStatusLabel(b.status)), 'ar');
      }

      return documentsSortDirection === 'asc' ? result : -result;
    });
    return copy;
  }, [documents, documentsSortDirection, documentsSortKey]);

  const totalDocumentPages = useMemo(
    () => Math.max(1, Math.ceil(sortedDocuments.length / documentsPageSize)),
    [documentsPageSize, sortedDocuments.length]
  );

  const pagedDocuments = useMemo(() => {
    const start = (documentsPage - 1) * documentsPageSize;
    return sortedDocuments.slice(start, start + documentsPageSize);
  }, [documentsPage, documentsPageSize, sortedDocuments]);

  const toggleDocumentsSort = (key: DocumentSortKey) => {
    if (documentsSortKey === key) {
      setDocumentsSortDirection((prev) => (prev === 'asc' ? 'desc' : 'asc'));
      return;
    }
    setDocumentsSortKey(key);
    setDocumentsSortDirection('asc');
  };

  const sortIndicator = (key: DocumentSortKey) => {
    if (documentsSortKey !== key) return '↕';
    return documentsSortDirection === 'asc' ? '↑' : '↓';
  };

  const fetchTemplates = async () => {
    setLoadingTemplates(true);
    try {
      const statusParam = templateStatusFilter === 'all' ? '' : `&status=${templateStatusFilter}`;
      const response = await fetch(`/api/admin/expense-recurring/templates?page=1&pageSize=200${statusParam}`);
      if (!response.ok) throw new Error('تعذر جلب القوالب');
      const data = await response.json();
      const items = Array.isArray(data?.items) ? data.items : [];
      setTemplates(items as RecurringExpenseTemplate[]);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب القوالب',
        variant: 'destructive',
      });
    } finally {
      setLoadingTemplates(false);
    }
  };

  const fetchDocuments = async () => {
    setLoadingDocuments(true);
    try {
      const statusParam = documentStatusFilter === 'all' ? '' : `&status=${documentStatusFilter}`;
      const response = await fetch(`/api/admin/expense-recurring/documents?page=1&pageSize=300${statusParam}`);
      if (!response.ok) throw new Error('تعذر جلب المستندات');
      const data = await response.json();
      const nextDocs = Array.isArray(data?.items) ? (data.items as ExpenseDocument[]) : [];
      setDocuments(nextDocs);

      if (nextDocs.length > 0 && !nextDocs.some((d) => d.id === selectedDocumentId)) {
        setSelectedDocumentId(nextDocs[0].id);
      }
      if (nextDocs.length === 0) {
        setSelectedDocumentId('');
      }
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب المستندات',
        variant: 'destructive',
      });
    } finally {
      setLoadingDocuments(false);
    }
  };

  const fetchPayments = async (documentId: string) => {
    if (!documentId) {
      setPayments([]);
      return;
    }
    setLoadingPayments(true);
    try {
      const response = await fetch(`/api/admin/expense-recurring/documents/${encodeURIComponent(documentId)}/payments`);
      if (!response.ok) throw new Error('تعذر جلب الدفعات');
      const data = await response.json();
      const items = Array.isArray(data?.items) ? data.items : [];
      setPayments(items as ExpensePayment[]);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب الدفعات',
        variant: 'destructive',
      });
    } finally {
      setLoadingPayments(false);
    }
  };

  const fetchHistory = async (documentId: string) => {
    if (!documentId) {
      setHistory([]);
      return;
    }

    setLoadingHistory(true);
    try {
      const response = await fetch(`/api/admin/expense-recurring/documents/${encodeURIComponent(documentId)}/history`);
      if (!response.ok) throw new Error('تعذر جلب السجل');
      const data = await response.json();
      const items = Array.isArray(data?.items) ? data.items : [];
      setHistory(items as ExpenseDocumentHistoryEntry[]);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب السجل',
        variant: 'destructive',
      });
    } finally {
      setLoadingHistory(false);
    }
  };

  useEffect(() => {
    void fetchTemplates();
  }, [templateStatusFilter]);

  useEffect(() => {
    void fetchDocuments();
  }, [documentStatusFilter]);

  useEffect(() => {
    setDocumentsPage(1);
  }, [documentStatusFilter, documentsPageSize]);

  useEffect(() => {
    if (documentsPage > totalDocumentPages) {
      setDocumentsPage(totalDocumentPages);
    }
  }, [documentsPage, totalDocumentPages]);

  useEffect(() => {
    void fetchPayments(selectedDocumentId);
  }, [selectedDocumentId]);

  useEffect(() => {
    void fetchHistory(selectedDocumentId);
  }, [selectedDocumentId]);

  const createTemplate = async () => {
    if (!templateName || !templateExpenseAccountCode || !templateStartDate) {
      toast({ title: 'تنبيه', description: 'الاسم وحساب المصروف وتاريخ البداية حقول مطلوبة', variant: 'destructive' });
      return;
    }

    const response = await fetch('/api/admin/expense-recurring/templates', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: templateName,
        expenseItemId: templateExpenseItemId || undefined,
        expenseAccountCode: templateExpenseAccountCode,
        payableAccountCode: templatePayableAccountCode || '2130',
        defaultAmount: Number(templateDefaultAmount || 0),
        frequency: templateFrequency,
        intervalCount: Number(templateIntervalCount || 1),
        startDate: templateStartDate,
        dayOfMonth: templateDayOfMonth ? Number(templateDayOfMonth) : undefined,
        monthOfYear: templateFrequency === 'yearly' && templateMonthOfYear ? Number(templateMonthOfYear) : undefined,
        approvalPolicy: templateApprovalPolicy,
        autoSubmitForApproval: templateAutoSubmit,
      }),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر إنشاء القالب'), variant: 'destructive' });
      return;
    }

    toast({ title: 'نجاح', description: 'تم إنشاء القالب الدوري' });
    setTemplateName('');
    setTemplateExpenseItemId('');
    setTemplateDefaultAmount('0');
    setTemplateDayOfMonth('');
    setTemplateMonthOfYear('');
    await fetchTemplates();
  };

  const generateDocuments = async () => {
    const response = await fetch('/api/admin/expense-recurring/generate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ asOfDate: generateAsOfDate || undefined }),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر التوليد'), variant: 'destructive' });
      return;
    }

    const data = await response.json();
    const generatedCount = Array.isArray(data?.generated) ? data.generated.length : 0;
    toast({ title: 'تم', description: `تم توليد ${generatedCount} مستند` });
    await fetchDocuments();
    await fetchTemplates();
  };

  const runDocumentAction = async (documentId: string, action: 'submit' | 'approve' | 'reject' | 'post') => {
    const payload: Record<string, unknown> = {};

    if (action === 'reject') {
      const reason = window.prompt('سبب الرفض:');
      if (!reason) return;
      payload.reason = reason;
    }

    if (action === 'post') {
      payload.postingDate = new Date().toISOString().slice(0, 10);
    }

    const response = await fetch(`/api/admin/expense-recurring/documents/${encodeURIComponent(documentId)}/${action}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'فشلت العملية'), variant: 'destructive' });
      return;
    }

    toast({ title: 'نجاح', description: 'تم تنفيذ العملية' });
    await fetchDocuments();
    await fetchHistory(selectedDocumentId);
  };

  const addPayment = async () => {
    if (!selectedDocumentId || !paymentAmount || !paymentAccountCode) {
      toast({ title: 'تنبيه', description: 'اختر مستندًا وأدخل المبلغ وحساب السداد', variant: 'destructive' });
      return;
    }

    const response = await fetch(`/api/admin/expense-recurring/documents/${encodeURIComponent(selectedDocumentId)}/payments`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        paymentDate: paymentDate || new Date().toISOString().slice(0, 10),
        amount: Number(paymentAmount || 0),
        paymentMethod,
        accountCode: paymentAccountCode,
        referenceNumber: paymentReference || undefined,
      }),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر تسجيل الدفعة'), variant: 'destructive' });
      return;
    }

    toast({ title: 'نجاح', description: 'تم تسجيل الدفعة' });
    setPaymentAmount('');
    setPaymentReference('');
    await fetchDocuments();
    await fetchPayments(selectedDocumentId);
    await fetchHistory(selectedDocumentId);
  };

  const exportHistoryCsv = () => {
    if (!selectedDocument) {
      toast({ title: 'تنبيه', description: 'اختر مستندا أولا', variant: 'destructive' });
      return;
    }

    if (filteredHistory.length === 0) {
      toast({ title: 'تنبيه', description: 'لا توجد بيانات سجل للتصدير', variant: 'destructive' });
      return;
    }

    const headers = ['الوقت', 'الحدث', 'من حالة', 'إلى حالة', 'بواسطة', 'ملاحظة'];
    const rows = filteredHistory.map((entry) => [
      String(entry.createdAt || '').replace('T', ' ').slice(0, 19),
      getHistoryActionLabel(entry.action),
      getStatusLabel(entry.fromStatus || undefined),
      getStatusLabel(entry.toStatus),
      entry.actorName || entry.actorId || '-',
      entry.note || '-',
    ]);

    const csv = [headers, ...rows]
      .map((row) => row.map((cell) => escapeCsvCell(cell)).join(','))
      .join('\r\n');

    const blob = new Blob([`\uFEFF${csv}`], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    const safeDocId = String(selectedDocument.id || 'document').replace(/[^a-zA-Z0-9-_]/g, '_');
    const stamp = new Date().toISOString().slice(0, 10);
    link.href = url;
    link.download = `expense-history-${safeDocId}-${stamp}.csv`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);

    toast({ title: 'نجاح', description: 'تم تصدير سجل التدقيق إلى CSV' });
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>إنشاء قالب مصروف دوري</CardTitle>
          <CardDescription>عرّف القالب مرة واحدة ليتم توليد المستندات شهريًا أو سنويًا تلقائيًا.</CardDescription>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
          <div className="space-y-1">
            <Label>اسم القالب</Label>
            <Input value={templateName} onChange={(e) => setTemplateName(e.target.value)} placeholder="مثال: إيجار المكتب" />
          </div>

          <div className="space-y-1">
            <Label>عنصر المصروف</Label>
            <Select value={templateExpenseItemId || 'none'} onValueChange={(v) => setTemplateExpenseItemId(v === 'none' ? '' : v)}>
              <SelectTrigger><SelectValue placeholder="اختياري" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">بدون ربط</SelectItem>
                {Array.isArray(expenseItems) && expenseItems.map((item) => (
                  <SelectItem key={item.id} value={item.id}>{item.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1">
            <Label>حساب المصروف</Label>
            <Select value={templateExpenseAccountCode || 'none'} onValueChange={(v) => setTemplateExpenseAccountCode(v === 'none' ? '' : v)}>
              <SelectTrigger><SelectValue placeholder="اختر حساب" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">اختر</SelectItem>
                {Array.isArray(expenseAccountOptions) && expenseAccountOptions.map((a) => (
                  <SelectItem key={a.id} value={a.code}>{a.code} - {a.nameAr || a.nameEn}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1">
            <Label>حساب الدائن/المستحق</Label>
            <Select value={templatePayableAccountCode || 'none'} onValueChange={(v) => setTemplatePayableAccountCode(v === 'none' ? '' : v)}>
              <SelectTrigger><SelectValue placeholder="اختر حساب" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">اختر</SelectItem>
                {Array.isArray(payableAccountOptions) && payableAccountOptions.map((a) => (
                  <SelectItem key={a.id} value={a.code}>{a.code} - {a.nameAr || a.nameEn}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1">
            <Label>المبلغ الافتراضي</Label>
            <Input type="number" value={templateDefaultAmount} onChange={(e) => setTemplateDefaultAmount(e.target.value)} />
          </div>

          <div className="space-y-1">
            <Label>التكرار</Label>
            <Select value={templateFrequency} onValueChange={(v) => setTemplateFrequency(v as Frequency)}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="monthly">شهري</SelectItem>
                <SelectItem value="yearly">سنوي</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1">
            <Label>كل كم فترة</Label>
            <Input type="number" value={templateIntervalCount} onChange={(e) => setTemplateIntervalCount(e.target.value)} />
          </div>

          <div className="space-y-1">
            <Label>تاريخ البداية</Label>
            <Input type="date" value={templateStartDate} onChange={(e) => setTemplateStartDate(e.target.value)} />
          </div>

          <div className="space-y-1">
            <Label>يوم الشهر</Label>
            <Input type="number" value={templateDayOfMonth} onChange={(e) => setTemplateDayOfMonth(e.target.value)} placeholder="1-31" />
          </div>

          <div className="space-y-1">
            <Label>شهر السنة (للسنوي)</Label>
            <Input type="number" value={templateMonthOfYear} onChange={(e) => setTemplateMonthOfYear(e.target.value)} placeholder="1-12" disabled={templateFrequency !== 'yearly'} />
          </div>

          <div className="space-y-1">
            <Label>سياسة الاعتماد</Label>
            <Select value={templateApprovalPolicy} onValueChange={(v) => setTemplateApprovalPolicy(v as ApprovalPolicy)}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">بدون اعتماد</SelectItem>
                <SelectItem value="single_step">اعتماد خطوة واحدة</SelectItem>
                <SelectItem value="two_step">اعتماد خطوتين</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center gap-2 pt-6">
            <Switch checked={templateAutoSubmit} onCheckedChange={setTemplateAutoSubmit} />
            <Label>إرسال تلقائي للاعتماد</Label>
          </div>

          <div className="flex items-end">
            <Button onClick={createTemplate} className="w-full">حفظ القالب</Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>توليد المستندات الدورية</CardTitle>
          <CardDescription>توليد المستندات المستحقة حتى تاريخ محدد.</CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col md:flex-row gap-3 md:items-end">
          <div className="space-y-1">
            <Label>حتى تاريخ</Label>
            <Input type="date" value={generateAsOfDate} onChange={(e) => setGenerateAsOfDate(e.target.value)} />
          </div>
          <Button onClick={generateDocuments}>توليد الآن</Button>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>القوالب</CardTitle>
          <CardDescription>مراجعة القوالب الحالية وحالة الجدولة.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="w-56">
            <Label>تصفية الحالة</Label>
            <Select value={templateStatusFilter} onValueChange={(v) => setTemplateStatusFilter(v as TemplateStatus | 'all')}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">الكل</SelectItem>
                <SelectItem value="active">نشط</SelectItem>
                <SelectItem value="paused">موقوف</SelectItem>
                <SelectItem value="closed">مغلق</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>الاسم</TableHead>
                <TableHead>التكرار</TableHead>
                <TableHead>المبلغ</TableHead>
                <TableHead>التشغيل القادم</TableHead>
                <TableHead>الحالة</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loadingTemplates ? (
                <TableRow><TableCell colSpan={5}>جاري التحميل...</TableCell></TableRow>
              ) : !Array.isArray(templates) || templates.length === 0 ? (
                <TableRow><TableCell colSpan={5}>لا توجد قوالب</TableCell></TableRow>
              ) : (
                templates.map((t) => (
                  <TableRow key={t.id}>
                    <TableCell>{t.name}</TableCell>
                    <TableCell>{t.frequency === 'monthly' ? 'شهري' : 'سنوي'}</TableCell>
                    <TableCell>{formatAmount(t.defaultAmount)}</TableCell>
                    <TableCell>{formatDateDDMMYYYY(t.nextRunDate)}</TableCell>
                    <TableCell><Badge variant={statusBadgeVariant(t.status)}>{t.status}</Badge></TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>مستندات المصروف</CardTitle>
          <CardDescription>إدارة دورة المستند: إرسال، اعتماد، ترحيل.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="w-64">
            <Label>تصفية الحالة</Label>
            <Select value={documentStatusFilter} onValueChange={setDocumentStatusFilter}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">الكل</SelectItem>
                <SelectItem value="draft">draft</SelectItem>
                <SelectItem value="pending_approval">pending_approval</SelectItem>
                <SelectItem value="approved">approved</SelectItem>
                <SelectItem value="rejected">rejected</SelectItem>
                <SelectItem value="posted">posted</SelectItem>
                <SelectItem value="partially_paid">partially_paid</SelectItem>
                <SelectItem value="paid">paid</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>
                  <button type="button" className="inline-flex items-center gap-1" onClick={() => toggleDocumentsSort('description')}>
                    الوصف {sortIndicator('description')}
                  </button>
                </TableHead>
                <TableHead>
                  <button type="button" className="inline-flex items-center gap-1" onClick={() => toggleDocumentsSort('period')}>
                    الفترة {sortIndicator('period')}
                  </button>
                </TableHead>
                <TableHead>
                  <button type="button" className="inline-flex items-center gap-1" onClick={() => toggleDocumentsSort('amount')}>
                    المبلغ {sortIndicator('amount')}
                  </button>
                </TableHead>
                <TableHead>
                  <button type="button" className="inline-flex items-center gap-1" onClick={() => toggleDocumentsSort('paidAmount')}>
                    المدفوع {sortIndicator('paidAmount')}
                  </button>
                </TableHead>
                <TableHead>
                  <button type="button" className="inline-flex items-center gap-1" onClick={() => toggleDocumentsSort('status')}>
                    الحالة {sortIndicator('status')}
                  </button>
                </TableHead>
                <TableHead>إجراءات</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loadingDocuments ? (
                <TableRow><TableCell colSpan={6}>جاري التحميل...</TableCell></TableRow>
              ) : !Array.isArray(pagedDocuments) || pagedDocuments.length === 0 ? (
                <TableRow><TableCell colSpan={6}>لا توجد مستندات</TableCell></TableRow>
              ) : (
                pagedDocuments.map((d) => (
                  <TableRow
                    key={d.id}
                    className={selectedDocumentId === d.id ? 'bg-muted/60' : ''}
                    onClick={() => setSelectedDocumentId(d.id)}
                  >
                    <TableCell>{d.description}</TableCell>
                    <TableCell>{d.periodYear}-{String(d.periodMonth).padStart(2, '0')}</TableCell>
                    <TableCell>{formatAmount(d.amount)}</TableCell>
                    <TableCell>{formatAmount(d.paidAmount)}</TableCell>
                    <TableCell><Badge variant={statusBadgeVariant(d.status)}>{getStatusLabel(d.status)}</Badge></TableCell>
                    <TableCell className="space-x-1 rtl:space-x-reverse">
                      <Button size="sm" variant="outline" onClick={(e) => { e.stopPropagation(); void runDocumentAction(d.id, 'submit'); }}>إرسال</Button>
                      <Button size="sm" variant="outline" onClick={(e) => { e.stopPropagation(); void runDocumentAction(d.id, 'approve'); }}>اعتماد</Button>
                      <Button size="sm" variant="outline" onClick={(e) => { e.stopPropagation(); void runDocumentAction(d.id, 'reject'); }}>رفض</Button>
                      <Button size="sm" onClick={(e) => { e.stopPropagation(); void runDocumentAction(d.id, 'post'); }}>ترحيل</Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
            <div className="text-xs text-muted-foreground">
              صفحة {documentsPage} من {totalDocumentPages} • إجمالي {sortedDocuments.length} مستند
            </div>
            <div className="flex items-center gap-2">
              <Select value={String(documentsPageSize)} onValueChange={(v) => setDocumentsPageSize(Number(v))}>
                <SelectTrigger className="h-8 w-32"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="10">10 / صفحة</SelectItem>
                  <SelectItem value="20">20 / صفحة</SelectItem>
                  <SelectItem value="50">50 / صفحة</SelectItem>
                </SelectContent>
              </Select>
              <Button
                size="sm"
                variant="outline"
                onClick={() => setDocumentsPage((p) => Math.max(1, p - 1))}
                disabled={documentsPage <= 1}
              >
                السابق
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => setDocumentsPage((p) => Math.min(totalDocumentPages, p + 1))}
                disabled={documentsPage >= totalDocumentPages}
              >
                التالي
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>دفعات المستند المحدد</CardTitle>
          <CardDescription>{selectedDocument ? `المستند: ${selectedDocument.description}` : 'اختر مستندًا من الجدول بالأعلى'}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
            <div className="space-y-1">
              <Label>تاريخ الدفعة</Label>
              <Input type="date" value={paymentDate} onChange={(e) => setPaymentDate(e.target.value)} />
            </div>

            <div className="space-y-1">
              <Label>المبلغ</Label>
              <Input type="number" value={paymentAmount} onChange={(e) => setPaymentAmount(e.target.value)} />
            </div>

            <div className="space-y-1">
              <Label>طريقة السداد</Label>
              <Select value={paymentMethod} onValueChange={(v) => setPaymentMethod(v as PaymentMethod)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="cash">cash</SelectItem>
                  <SelectItem value="bank">bank</SelectItem>
                  <SelectItem value="credit">credit</SelectItem>
                  <SelectItem value="mixed">mixed</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1">
              <Label>حساب السداد</Label>
              <Select value={paymentAccountCode || 'none'} onValueChange={(v) => setPaymentAccountCode(v === 'none' ? '' : v)}>
                <SelectTrigger><SelectValue placeholder="اختر حساب" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">اختر</SelectItem>
                  {Array.isArray(paymentAccountOptions) && paymentAccountOptions.map((a) => (
                    <SelectItem key={a.id} value={a.code}>{a.code} - {a.nameAr || a.nameEn}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1">
              <Label>مرجع</Label>
              <Input value={paymentReference} onChange={(e) => setPaymentReference(e.target.value)} placeholder="اختياري" />
            </div>
          </div>

          <Button onClick={addPayment} disabled={!selectedDocumentId}>تسجيل دفعة</Button>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>التاريخ</TableHead>
                <TableHead>المبلغ</TableHead>
                <TableHead>الطريقة</TableHead>
                <TableHead>الحساب</TableHead>
                <TableHead>المرجع</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loadingPayments ? (
                <TableRow><TableCell colSpan={5}>جاري التحميل...</TableCell></TableRow>
              ) : !Array.isArray(payments) || payments.length === 0 ? (
                <TableRow><TableCell colSpan={5}>لا توجد دفعات</TableCell></TableRow>
              ) : (
                payments.map((p) => (
                  <TableRow key={p.id}>
                    <TableCell>{formatDateDDMMYYYY(p.paymentDate)}</TableCell>
                    <TableCell>{formatAmount(p.amount)}</TableCell>
                    <TableCell>{p.paymentMethod}</TableCell>
                    <TableCell>{p.accountCode}</TableCell>
                    <TableCell>{p.referenceNumber || '-'}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>سجل حالة المستند</CardTitle>
          <CardDescription>{selectedDocument ? `المستند: ${selectedDocument.description}` : 'اختر مستندًا من الجدول بالأعلى'}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex justify-end">
            <Button variant="outline" onClick={exportHistoryCsv} disabled={!selectedDocument || filteredHistory.length === 0}>
              تصدير CSV
            </Button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label>تصفية الحدث</Label>
              <Select value={historyActionFilter} onValueChange={setHistoryActionFilter}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">كل الأحداث</SelectItem>
                  <SelectItem value="created">{getHistoryActionLabel('created')}</SelectItem>
                  <SelectItem value="submitted">{getHistoryActionLabel('submitted')}</SelectItem>
                  <SelectItem value="approved">{getHistoryActionLabel('approved')}</SelectItem>
                  <SelectItem value="rejected">{getHistoryActionLabel('rejected')}</SelectItem>
                  <SelectItem value="posted">{getHistoryActionLabel('posted')}</SelectItem>
                  <SelectItem value="payment">{getHistoryActionLabel('payment')}</SelectItem>
                  <SelectItem value="status_changed">{getHistoryActionLabel('status_changed')}</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label>بحث في السجل</Label>
              <Input
                value={historyQuery}
                onChange={(e) => setHistoryQuery(e.target.value)}
                placeholder="ابحث باسم المستخدم أو الملاحظة أو الحالة"
              />
            </div>
          </div>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>الوقت</TableHead>
                <TableHead>الحدث</TableHead>
                <TableHead>من</TableHead>
                <TableHead>إلى</TableHead>
                <TableHead>بواسطة</TableHead>
                <TableHead>ملاحظة</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loadingHistory ? (
                <TableRow><TableCell colSpan={6}>جاري التحميل...</TableCell></TableRow>
              ) : !Array.isArray(filteredHistory) || filteredHistory.length === 0 ? (
                <TableRow><TableCell colSpan={6}>لا يوجد سجل بعد</TableCell></TableRow>
              ) : (
                filteredHistory.map((entry) => (
                  <TableRow key={entry.id}>
                    <TableCell>{String(entry.createdAt || '').replace('T', ' ').slice(0, 19)}</TableCell>
                    <TableCell>{getHistoryActionLabel(entry.action)}</TableCell>
                    <TableCell>{getStatusLabel(entry.fromStatus || undefined)}</TableCell>
                    <TableCell><Badge variant={statusBadgeVariant(entry.toStatus)}>{getStatusLabel(entry.toStatus)}</Badge></TableCell>
                    <TableCell>{entry.actorName || entry.actorId || '-'}</TableCell>
                    <TableCell>{entry.note || '-'}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
