import React, { useState, useEffect } from 'react';
import { ModuleHeader } from './ModuleHeader';
import { PaymentAuthEntry, PaymentRequestType, RolePermission, FixedExpenseTemplate } from '../types';
import { supabase } from '../services/supabaseClient';
import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";
import { PaymentAuthModal } from './PaymentAuthModal';
import { formatDisplayDate, formatDisplayYear } from '../utils/dateUtils';
import { Language } from '../translations';

interface PaymentAuthProps {
  entries: PaymentAuthEntry[];
  onRefresh: () => void;
  currentUser: string | null;
  userRole: string;
  permissions?: RolePermission[];
  language?: string;
}

export const PaymentAuth: React.FC<PaymentAuthProps> = ({
  entries,
  onRefresh,
  currentUser,
  userRole,
  permissions,
  language = 'zh-TW'
}) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingEntry, setEditingEntry] = useState<PaymentAuthEntry | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [printData, setPrintData] = useState<PaymentAuthEntry | null>(null);
  const [selectedPaymentIds, setSelectedPaymentIds] = useState<string[]>([]);

  // 常用費用管理狀態
  const [isFixedExpenseModalOpen, setIsFixedExpenseModalOpen] = useState(false);
  const [fixedTemplates, setFixedTemplates] = useState<FixedExpenseTemplate[]>([]);
  const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [isManagingCategories, setIsManagingCategories] = useState(false);
  const [newTemplate, setNewTemplate] = useState({ name: '', amount: 0, category: '服務' });

  // 權限檢查輔助函數
  const hasPermission = (
    code: string,
    action: 'view' | 'create' | 'edit' | 'delete' = 'view'
  ) => {
    if (userRole === 'ADMIN') return true;
    const p = permissions?.find(up => up.permission?.code === code);
    if (!p) return false;
    return p[`can_${action}` as keyof RolePermission] === true;
  };

  const canCreatePayment = hasPermission('payment_auth', 'create');
  const canEditPayment = hasPermission('payment_auth', 'edit');
  const canDeletePayment = hasPermission('payment_auth', 'delete');

  // 審核權限：admin 或具備編輯權限的人可審核
  const isAdmin = canEditPayment;

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    const { data } = await supabase
      .from('fixed_expense_categories')
      .select('*')
      .order('name');

    if (data) setCategories(data);
  };

  const handleAddCategory = async () => {
    if (!newCategoryName) return;

    const { error } = await supabase
      .from('fixed_expense_categories')
      .insert([{ name: newCategoryName }]);

    if (error) {
      alert(
        language === 'zh-TW'
          ? "新增失敗（名稱重複或其他錯誤）: " + error.message
          : "Add failed: " + error.message
      );
    } else {
      setNewCategoryName('');
      fetchCategories();
    }
  };

  const handleDeleteCategory = async (id: string) => {
    if (!confirm(language === 'zh-TW' ? "確定要刪除此類別嗎？" : "Are you sure to delete this category?")) return;

    const { error } = await supabase
      .from('fixed_expense_categories')
      .delete()
      .eq('id', id);

    if (error) {
      alert(language === 'zh-TW' ? "刪除失敗" : "Delete failed");
    } else {
      fetchCategories();
    }
  };

  // 當 printData 變動，且存在時開始 PDF 產生流程
  useEffect(() => {
    if (printData && isGenerating) {
      const generatePDF = async () => {
        await new Promise(resolve => setTimeout(resolve, 800));

        const element = document.getElementById(`payment-print-template-${printData.id}`);
        if (!element) {
          console.error("Payment Template element not found");
          setIsGenerating(false);
          setPrintData(null);
          return;
        }

        try {
          const canvas = await html2canvas(element, {
            scale: 2,
            useCORS: true,
            backgroundColor: "#ffffff",
            logging: false,
            width: element.offsetWidth,
            height: element.offsetHeight
          });

          const imgData = canvas.toDataURL("image/png");
          const pdf = new jsPDF("p", "mm", "a4");
          const pdfWidth = 210;
          const pageHeight = 297;
          const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

          let position = 0;
          let heightLeft = pdfHeight;

          pdf.addImage(imgData, "PNG", 0, position, pdfWidth, pdfHeight);
          heightLeft -= pageHeight;

          while (heightLeft > 0) {
            position -= pageHeight;
            pdf.addPage();
            pdf.addImage(imgData, "PNG", 0, position, pdfWidth, pdfHeight);
            heightLeft -= pageHeight;
          }

          pdf.save(
            language === 'zh-TW'
              ? `請款單_${printData.type}_${printData.id}.pdf`
              : `Payment_Auth_${printData.type}_${printData.id}.pdf`
          );
        } catch (error) {
          console.error("PDF Generation Error:", error);
          alert(
            language === 'zh-TW'
              ? "PDF 產生失敗，請檢查權限或稍後再試。"
              : "PDF generation failed."
          );
        } finally {
          setIsGenerating(false);
          setPrintData(null);
        }
      };

      generatePDF();
    }
  }, [printData, isGenerating, language]);

  const getTypeColor = (type: PaymentRequestType) => {
    switch (type) {
      case '業績結算':
        return 'bg-indigo-50 text-indigo-600 border-indigo-100';
      case '進貨請款':
        return 'bg-emerald-50 text-emerald-600 border-emerald-100';
      case '費用支出':
        return 'bg-amber-50 text-amber-600 border-amber-100';
      default:
        return 'bg-slate-50 text-slate-600 border-slate-100';
    }
  };

  const handlePrint = (entry: PaymentAuthEntry) => {
    setIsGenerating(true);
    setPrintData(entry);
  };

  const handleEdit = (entry: PaymentAuthEntry) => {
    setEditingEntry(entry);
    setIsModalOpen(true);
  };

  const handleStatusChange = async (id: string, newStatus: string) => {
    if (!isAdmin) return;

    // 如果被標記為已支付，先更新獨立支付資訊表
    if (newStatus === 'Paid') {
      const { error: payError } = await supabase
        .from('payment_auth_payments')
        .upsert({
          payment_auth_id: id,
          is_paid: true,
          paid_at: new Date().toISOString(),
          paid_by: currentUser || 'System'
        });

      if (payError) {
        console.error("支付狀態變更失敗", payError);
        alert(
          language === 'zh-TW'
            ? "支付狀態變更失敗：" + payError.message
            : "Payment status update failed: " + payError.message
        );
        return;
      }
    }

    const { error } = await supabase
      .from('payment_auths')
      .update({ status: newStatus })
      .eq('id', id);

    if (error) {
      console.warn("主表狀態更新失敗(可能權限不足):", error.message);
      if (newStatus !== 'Paid') {
        alert(
          language === 'zh-TW'
            ? "更新失敗：" + error.message
            : "Update failed: " + error.message
        );
        return;
      }
    }

    onRefresh();
  };

  const fetchTemplates = async () => {
    const { data } = await supabase
      .from('fixed_expense_templates')
      .select('*')
      .order('name');

    if (data) setFixedTemplates(data);
  };

  useEffect(() => {
    if (isFixedExpenseModalOpen) fetchTemplates();
  }, [isFixedExpenseModalOpen]);

  const handleAddTemplate = async () => {
    if (!newTemplate.name) return;

    const { error } = await supabase
      .from('fixed_expense_templates')
      .insert([newTemplate]);

    if (!error) {
      setNewTemplate({ name: '', amount: 0, category: '服務' });
      fetchTemplates();
    } else {
      console.error("Template Error:", error);
      alert("新增項目失敗: " + error.message);
    }
  };

  const handleDeleteTemplate = async (id: string) => {
    if (!window.confirm(language === 'zh-TW' ? "確定要刪除此範本嗎？" : "Are you sure to delete this template?")) return;

    const { error } = await supabase
      .from('fixed_expense_templates')
      .delete()
      .eq('id', id);

    if (!error) fetchTemplates();
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm(language === 'zh-TW' ? "確定刪除此紀錄？" : "Are you sure to delete this record?")) return;

    const { error } = await supabase
      .from('payment_auths')
      .delete()
      .eq('id', id);

    if (error) {
      alert(
        language === 'zh-TW'
          ? "刪除失敗: " + error.message
          : "Delete failed: " + error.message
      );
    } else {
      onRefresh();
    }
  };


  const handleExportSelectedPayments = () => {
    const selected = entries.filter(e => selectedPaymentIds.includes(e.id));
    if (selected.length === 0) {
      alert(language === 'zh-TW' ? '請先勾選要匯出的請款資料。' : 'Please select payment requests to export first.');
      return;
    }
    const blob = new Blob([JSON.stringify(selected, null, 2)], { type: 'application/json;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `SUPER-ERP_payment_requests_${selected.length}_${new Date().toISOString().slice(0, 10)}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      {isGenerating && (
        <div className="fixed inset-0 bg-slate-900/80 z-[10000] flex items-center justify-center animate-in fade-in duration-300">
          <div className="bg-white dark:bg-slate-900 p-10 rounded-2xl shadow-2xl flex flex-col items-center gap-5 border border-slate-100 dark:border-slate-800">
            <div className="w-12 h-12 border-4 border-indigo-600 dark:border-indigo-400 border-t-transparent rounded-full animate-spin"></div>
            <div className="text-center">
              <p className="text-lg font-black text-slate-800 dark:text-slate-100 tracking-tight">
                {language === 'zh-TW' ? '文件產生中...' : 'Generating Document...'}
              </p>
              <p className="text-xs text-slate-400 dark:text-slate-500 font-bold uppercase tracking-widest mt-1">
                SUPER ERP DOCUMENT SERVICE
              </p>
            </div>
          </div>
        </div>
      )}

      <ModuleHeader
        title={language === 'zh-TW' ? "請款審核中心" : "Payment Request Center"}
        description={
          language === 'zh-TW'
            ? "發起與審核請款單。審核權限：admin, Boss。"
            : "Create or audit payment requests. Audit perm: admin, Boss."
        }
        actions={
          <div className="flex gap-2">
            <button onClick={handleExportSelectedPayments} className="px-4 py-2.5 bg-white dark:bg-slate-900 border border-indigo-200 dark:border-indigo-800 rounded-xl text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-950/30 shadow-sm transition-all active:scale-95 font-black text-sm">
              {language === 'zh-TW' ? `匯出勾選 (${selectedPaymentIds.length})` : `Export Selected (${selectedPaymentIds.length})`}
            </button>
            <button
              onClick={onRefresh}
              className="p-2.5 bg-white dark:bg-slate-900 border border-slate-100 dark:border-slate-800 rounded-xl text-slate-400 dark:text-slate-500 hover:text-indigo-600 dark:hover:text-indigo-400 shadow-sm transition-all active:scale-95"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" strokeWidth="2.5" strokeLinecap="round" />
              </svg>
            </button>

            <button
              onClick={() => setIsFixedExpenseModalOpen(true)}
              title={language === 'zh-TW' ? "常用費用管理" : "Templates"}
              className="p-2.5 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800/50 rounded-xl text-emerald-600 dark:text-emerald-400 hover:bg-emerald-600 dark:hover:bg-emerald-500 hover:text-white shadow-sm transition-all active:scale-95 flex items-center gap-2 font-black text-xs uppercase tracking-tighter"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              {language === 'zh-TW' ? '常用費用' : 'Templates'}
            </button>

            {canCreatePayment && (
              <button
                onClick={() => {
                  setEditingEntry(null);
                  setIsModalOpen(true);
                }}
                className="bg-slate-900 dark:bg-indigo-600 text-white px-6 py-2.5 rounded-xl text-sm font-black shadow-xl hover:bg-black dark:hover:bg-indigo-700 transition-all flex items-center gap-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path d="M12 4v16m8-8H4" strokeWidth="3" strokeLinecap="round" />
                </svg>
                {language === 'zh-TW' ? '新增請款' : 'New Request'}
              </button>
            )}
          </div>
        }
      />

      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm overflow-hidden text-slate-700 dark:text-slate-300">
        <div className="overflow-x-auto">
          <table className="w-full text-left table-fixed">
            <thead className="sticky top-0 z-30">
              <tr className="bg-slate-50/80 dark:bg-slate-800/80 backdrop-blur-md text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] border-b border-slate-200 dark:border-slate-800">
                                <th className="px-4 py-5 w-[5%] text-center"><input type="checkbox" checked={entries.length > 0 && entries.every(e => selectedPaymentIds.includes(e.id))} onChange={ev => { const ids = entries.map(e => e.id); setSelectedPaymentIds(prev => ev.target.checked ? Array.from(new Set([...prev, ...ids])) : prev.filter(id => !ids.includes(id))); }} className="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" /></th>
                <th className="px-6 py-5 w-[15%]">{language === 'zh-TW' ? '公司 / 單號' : 'Co / ID'}</th>
                <th className="px-6 py-5 w-[18%]">{language === 'zh-TW' ? '請            <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
              {entries.map(e => (
                <tr key={e.id} className="hover:bg-slate-50/50 dark:hover:bg-slate-800/30 transition-all group">
                  <td className="px-4 py-6 text-center"><input type="checkbox" checked={selectedPaymentIds.includes(e.id)} onChange={ev => setSelectedPaymentIds(prev => ev.target.checked ? [...prev, e.id] : prev.filter(id => id !== e.id))} className="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" /></td>
                  <td className="px-6 py-6 overflow-hidden">
                    <span className={`px-2 py-0.5 rounded text-[10px] font-black border uppercase mb-1.5 inline-block whitespace-nowrap ${getTypeColor(e.type)}`}>
                      {language === 'zh-TW'
                        ? (e.type === '進貨請款' || e.type === '費用支出' ? '費用請款' : e.type)
                        : (e.type === '業績結算'
                          ? 'Bonus'
                          : 'Expense')}
                    </span>
                    <p className="font-mono text-[9px] font-black text-slate-300 dark:text-slate-600 truncate">
                      {e.id}
                    </p>
                  </td>     </thead>

            <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
              {entries.map(e => (
                <tr key={e.id} className="hover:bg-slate-50/50 dark:hover:bg-slate-800/30 transition-all group">
                  <td className="px-4 py-6 text-center"><input type="checkbox" checked={selectedPaymentIds.includes(e.id)} onChange={ev => setSelectedPaymentIds(prev => ev.target.checked ? [...prev, e.id] : prev.filter(id => id !== e.id))} className="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" /></td>

                  <td className="px-6 py-6">
                    <p className="text-lg font-black text-slate-800 dark:text-slate-100 truncate" title={e.requester}>
                      {e.requester}
                    </p>
                    <p className="text-[10px] text-slate-400 dark:text-slate-500 font-bold whitespace-nowrap">
                      {e.department} ｜ {formatDisplayDate(e.date, language as Language)}
                    </p>
                  </td>

                  <td className="p-6 text-right font-black text-xl text-slate-900 dark:text-slate-100">
                    $
                    {(e.type === '業績結算' && e.commissionRate != null)
                      ? Math.round((e.businessProfit || 0) * e.commissionRate).toLocaleString()
                      : (e.type === '進貨請款'
                        ? e.items.reduce((sum, i) => sum + (i.unitCost * i.quantity), 0).toLocaleString()
                        : (e.amount || 0).toLocaleString())}
                  </td>

                  {isAdmin && (
                    <td className="px-6 py-6 text-right">
                      {e.type !== '進貨請款' ? (
                        <>
                          <p
                            className="text-lg font-black text-indigo-600 dark:text-indigo-400"
                            title={language === 'zh-TW' ? "公司最終淨利" : "Net"}
                          >
                            ${(e.netProfit || 0).toLocaleString()}
                          </p>
                          <div className="flex flex-col gap-0 mt-1">
                            <p className="text-[10px] text-emerald-600 dark:text-emerald-500 font-bold whitespace-nowrap">
                              {language === 'zh-TW' ? '業績' : 'Sales'}: ${(e.businessProfit || 0).toLocaleString()}
                            </p>
                            <p className="text-[10px] text-slate-400 dark:text-slate-500 font-bold whitespace-nowrap">
                              {language === 'zh-TW' ? '毛利' : 'Inv'}: ${(e.grossProfit || 0).toLocaleString()}
                            </p>
                          </div>
                        </>
                      ) : (
                        <span className="text-[10px] font-bold text-slate-200 dark:text-slate-800 italic uppercase tracking-widest">
                          - N/A -
                        </span>
                      )}
                    </td>
                  )}

                  <td className="px-6 py-6 text-center">
                    <span
                      className={`px-4 py-1.5 rounded-full text-[11px] font-black border tracking-[0.15em] whitespace-nowrap inline-block min-w-[100px] shadow-sm ${(e.status === 'Paid' || e.payment_info?.is_paid)
                          ? 'bg-indigo-500 border-indigo-600 text-white'
                          : e.status === 'Approved'
                            ? 'bg-emerald-500 border-emerald-600 text-white'
                            : e.status === 'Rejected'
                              ? 'bg-rose-500 border-rose-600 text-white'
                              : 'bg-slate-50 dark:bg-slate-800 text-slate-400 dark:text-slate-500 border-slate-200 dark:border-slate-700'
                        }`}
                    >
                      {(e.status === 'Paid' || e.payment_info?.is_paid)
                        ? (language === 'zh-TW' ? '已支付' : 'Paid')
                        : e.status === 'Approved'
                          ? (language === 'zh-TW' ? '已核准' : 'Approved')
                          : e.status === 'Rejected'
                            ? (language === 'zh-TW' ? '已退回' : 'Rejected')
                            : (language === 'zh-TW' ? '審核中' : 'Pending')}
                    </span>

                    {e.payment_info?.is_paid && (
                      <div className="mt-2 text-[9px] text-slate-300 dark:text-slate-600 font-bold leading-tight">
                        <p className="truncate px-2">{e.payment_info.paid_by}</p>
                        <p>{formatDisplayDate(e.payment_info.paid_at, language as Language)}</p>
                      </div>
                    )}
                  </td>

                  <td className="px-6 py-6 text-center">
                    <div className="flex justify-center gap-1.5 whitespace-nowrap overflow-visible">
                      <button
                        onClick={() => handlePrint(e)}
                        title={language === 'zh-TW' ? "列印文件" : "Print"}
                        className="p-2 bg-white dark:bg-slate-800 border border-slate-100 dark:border-slate-800 rounded-xl text-slate-300 dark:text-slate-600 hover:text-indigo-600 dark:hover:text-indigo-400 shadow-sm transition-all active:scale-90"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" strokeWidth="2.5" />
                        </svg>
                      </button>

                      {canEditPayment && (
                        <button
                          onClick={() => handleEdit(e)}
                          className="p-2 bg-white dark:bg-slate-800 border border-slate-100 dark:border-slate-800 rounded-xl text-slate-300 dark:text-slate-600 hover:text-indigo-600 dark:hover:text-indigo-400 shadow-sm transition-all"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" strokeWidth="2.5" />
                          </svg>
                        </button>
                      )}

                      {isAdmin && e.status === 'Pending' && (
                        <>
                          <button
                            onClick={() => handleStatusChange(e.id, 'Approved')}
                            title={language === 'zh-TW' ? "核准" : "Approve"}
                            className="p-2 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-xl hover:bg-emerald-600 dark:hover:bg-emerald-500 hover:text-white transition-all shadow-sm"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path d="M5 13l4 4L19 7" strokeWidth="3" />
                            </svg>
                          </button>

                          <button
                            onClick={() => handleStatusChange(e.id, 'Rejected')}
                            title={language === 'zh-TW' ? "退回" : "Reject"}
                            className="p-2 bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 rounded-xl hover:bg-rose-600 dark:hover:bg-rose-500 hover:text-white transition-all shadow-sm"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path d="M6 18L18 6M6 6l12 12" strokeWidth="3" />
                            </svg>
                          </button>
                        </>
                      )}

                      {isAdmin && e.status === 'Approved' && !e.payment_info?.is_paid && (
                        <button
                          onClick={() => handleStatusChange(e.id, 'Paid')}
                          title={language === 'zh-TW' ? "標記為已支付" : "Mark as Paid"}
                          className="px-3 py-1.5 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 rounded-xl hover:bg-indigo-600 dark:hover:bg-indigo-500 hover:text-white transition-all flex items-center gap-1.5 shadow-sm"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                          <span className="text-[10px] font-black">
                            {language === 'zh-TW' ? '付款' : 'Pay'}
                          </span>
                        </button>
                      )}

                      {canDeletePayment && (
                        <button
                          onClick={() => handleDelete(e.id)}
                          className="p-2 bg-white dark:bg-slate-800 border border-slate-100 dark:border-slate-800 rounded-xl text-slate-400 dark:text-slate-500 hover:text-rose-600 dark:hover:text-rose-400 transition-all shadow-sm"
                          title={language === 'zh-TW' ? "刪除" : "Delete"}
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" strokeWidth="2.5" />
                          </svg>
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <PaymentAuthModal
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
          setEditingEntry(null);
        }}
        onRefresh={onRefresh}
        currentUser={currentUser}
        userRole={userRole}
        initialData={editingEntry}
        language={language}
      />

      {/* 隱藏 PDF 請款單模板 */}
      <div style={{ position: 'fixed', top: '100%', left: '100%', pointerEvents: 'none', zIndex: -1 }}>
        {printData && (
          <div
            id={`payment-print-template-${printData.id}`}
            style={{
              width: '210mm',
              padding: '10mm 20mm 20mm 20mm',
              backgroundColor: 'white',
              color: 'black',
              fontFamily: 'sans-serif',
              boxSizing: 'border-box'
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '2px solid black', paddingBottom: '10px', marginBottom: '15px' }}>
              <div>
                <h1 style={{ fontSize: '18px', fontWeight: '900', margin: '0' }}>{printData.entity}</h1>
                <p style={{ fontSize: '9px', color: '#666', margin: '3px 0 0', fontWeight: 'bold' }}>
                  INTERNAL EXPENDITURE VOUCHER
                </p>
              </div>
              <div style={{ textAlign: 'right' }}>
                <h2 style={{ fontSize: '20px', fontWeight: '900', margin: '0', color: '#1a1a1a' }}>
                  請款單
                </h2>
                <p style={{ fontSize: '10px', margin: '3px 0 0', fontWeight: 'black', color: '#444' }}>
                  NO: {printData.id}
                </p>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px', marginBottom: '15px', backgroundColor: '#f8fafc', padding: '12px', borderRadius: '10px' }}>
              <div style={{ borderRight: '1px solid #e2e8f0' }}>
                <p style={{ fontSize: '8px', fontWeight: '900', color: '#94a3b8', textTransform: 'uppercase', marginBottom: '6px' }}>
                  請款人資訊 REQUESTER
                </p>
                <div style={{ fontSize: '11px', lineHeight: '1.6' }}>
                  <p style={{ margin: '0' }}>部門：<span style={{ fontWeight: 'bold' }}>{printData.department}</span></p>
                  <p style={{ margin: '0' }}>請款人員：<span style={{ fontWeight: 'bold' }}>{printData.requester}</span></p>
                  <p style={{ margin: '0' }}>請款類別：<span style={{ fontWeight: 'bold', color: '#4f46e5' }}>{printData.type}</span></p>
                </div>
              </div>
              <div style={{ paddingLeft: '10px' }}>
                <p style={{ fontSize: '8px', fontWeight: '900', color: '#94a3b8', textTransform: 'uppercase', marginBottom: '6px' }}>
                  單據詳情 STATUS
                </p>
                <div style={{ fontSize: '11px', lineHeight: '1.6' }}>
                  <p style={{ margin: '0' }}>日期：<span style={{ fontWeight: 'bold' }}>{formatDisplayDate(printData.date, language as Language)}</span></p>
                  <p style={{ margin: '0' }}>審核狀態：<span style={{ fontWeight: 'bold', color: printData.status === 'Approved' ? '#059669' : '#d97706' }}>{printData.status === 'Approved' ? '已核准(Approved)' : '待審核(Pending)'}</span></p>
                  {printData.supplier && <p style={{ margin: '0' }}>供應廠商：<span style={{ fontWeight: 'bold' }}>{printData.supplier}</span></p>}
                </div>
              </div>
            </div>

            <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '15px' }}>
              <thead>
                <tr style={{ backgroundColor: '#1f2937', color: 'white' }}>
                  <th style={{ padding: '8px', textAlign: 'left', fontSize: '10px', fontWeight: '900' }}>日期 DATE</th>
                  <th style={{ padding: '8px', textAlign: 'left', fontSize: '10px', fontWeight: '900' }}>項目描述 DESCRIPTION</th>
                  <th style={{ padding: '8px', textAlign: 'center', fontSize: '10px', fontWeight: '900', width: '60px' }}>數量</th>
                  {printData.type === '業績結算' && (
                    <th style={{ padding: '8px', textAlign: 'right', fontSize: '10px', fontWeight: '900', width: '80px' }}>
                      業績成本 COST
                    </th>
                  )}
                  <th style={{ padding: '8px', textAlign: 'center', fontSize: '10px', fontWeight: '900', width: '100px' }}>發票編號</th>
                  <th style={{ padding: '8px', textAlign: 'right', fontSize: '10px', fontWeight: '900', width: '100px' }}>金額 AMOUNT</th>
                </tr>
              </thead>

              <tbody>
                {(printData.items || []).map((item, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid #eee', pageBreakInside: 'avoid' }}>
                    <td style={{ padding: '8px', fontSize: '10px', fontWeight: 'bold', color: '#666' }}>
                      {formatDisplayDate(item.date, language as Language)}
                    </td>
                    <td style={{ padding: '8px', fontSize: '11px', fontWeight: '500' }}>
                      {item.description}
                      <span style={{ fontSize: '8px', color: '#999', marginLeft: '6px' }}>{item.category}</span>
                    </td>
                    <td style={{ padding: '8px', textAlign: 'center', fontSize: '10px', fontWeight: 'bold' }}>
                      {item.quantity}
                    </td>
                    {printData.type === '業績結算' && (
                      <td style={{ padding: '8px', textAlign: 'right', fontSize: '11px', fontWeight: '900', color: '#d97706' }}>
                        ${(item.totalSalesCost || 0).toLocaleString()}
                      </td>
                    )}
                    <td style={{ padding: '8px', textAlign: 'center', fontSize: '10px', color: '#666', fontWeight: 'bold' }}>
                      {item.invoiceNumber || (item.hasInvoice ? '有發票' : '無發票')}
                    </td>
                    <td style={{ padding: '8px', textAlign: 'right', fontSize: '11px', fontWeight: '900' }}>
                      ${(printData.type === '進貨請款'
                        ? (item.unitCost * item.quantity)
                        : (item.totalAmount || item.amount)
                      ).toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>

              <tfoot>
                {printData.type !== '業績結算' && (
                  <tr style={{ backgroundColor: '#f8fafc', pageBreakInside: 'avoid', borderTop: '2px solid #e2e8f0' }}>
                    <td colSpan={4} style={{ padding: '12px', textAlign: 'right', fontSize: '12px', fontWeight: '900' }}>
                      請款總額 TOTAL (TWD):
                    </td>
                    <td style={{ padding: '12px', textAlign: 'right', fontSize: '16px', fontWeight: '900', color: '#4f46e5' }}>
                      ${(printData.type === '進貨請款'
                        ? printData.items.reduce((sum, i) => sum + (i.unitCost * i.quantity), 0)
                        : (printData.amount || 0)
                      ).toLocaleString()}
                    </td>
                  </tr>
                )}

                {printData.type === '業績結算' && (
                  <>
                    <tr style={{ backgroundColor: '#f8fafc', pageBreakInside: 'avoid', borderTop: '2px solid #e2e8f0' }}>
                      <td colSpan={4} style={{ padding: '8px 12px', textAlign: 'right', fontSize: '11px', fontWeight: '900', color: '#64748b' }}>
                        售價 (${((printData.businessProfit || 0) + (printData.totalSalesCost || 0)).toLocaleString()}) - 總業績成本 (${(printData.totalSalesCost || 0).toLocaleString()}) = 總業績
                      </td>
                      <td style={{ padding: '8px 12px', textAlign: 'right', fontSize: '14px', fontWeight: '900', color: '#059669' }}>
                        ${(printData.businessProfit || 0).toLocaleString()}
                      </td>
                    </tr>

                    <tr style={{ backgroundColor: '#eef2ff', pageBreakInside: 'avoid', borderTop: '1px solid #e2e8f0' }}>
                      <td colSpan={5} style={{ padding: '12px', textAlign: 'right', fontSize: '14px', fontWeight: '900', color: '#4f46e5' }}>
                        業績獎金 BONUS:
                        <span style={{ color: '#059669', margin: '0 8px' }}>
                          ${(printData.businessProfit || 0).toLocaleString()}
                        </span>
                        ×
                        <span style={{ color: '#d97706', margin: '0 8px' }}>
                          {printData.commissionRate != null ? `${printData.commissionRate * 100}%` : '預設值'}
                        </span>
                        =
                        <span style={{ fontSize: '18px', marginLeft: '12px' }}>
                          ${printData.commissionRate != null
                            ? Math.round((printData.businessProfit || 0) * printData.commissionRate).toLocaleString()
                            : '0'}
                        </span>
                      </td>
                    </tr>
                  </>
                )}
              </tfoot>
            </table>

            <div style={{ marginTop: '30px', display: 'flex', justifyContent: 'space-between', pageBreakInside: 'avoid' }}>
              <div style={{ width: '120px', borderTop: '1px solid black', paddingTop: '8px', textAlign: 'center' }}>
                <p style={{ fontSize: '9px', fontWeight: '900' }}>請款人簽名</p>
              </div>
              <div style={{ width: '120px', borderTop: '1px solid black', paddingTop: '8px', textAlign: 'center' }}>
                <p style={{ fontSize: '9px', fontWeight: '900' }}>會計簽核</p>
              </div>
              <div style={{ width: '120px', borderTop: '2px solid #4f46e5', paddingTop: '8px', textAlign: 'center' }}>
                <p style={{ fontSize: '9px', fontWeight: '900', color: '#4f46e5' }}>主管 / 老闆簽核</p>
              </div>
            </div>

            <div style={{ marginTop: '40px', borderTop: '1px solid #eee', paddingTop: '10px', textAlign: 'center', pageBreakInside: 'avoid' }}>
              <p style={{ fontSize: '9px', color: '#cbd5e1', fontWeight: 'bold' }}>
                Generated by SuperERP ｜ Internal Doc: {printData.id} ｜ Printed on: {new Date().getFullYear()} ({formatDisplayYear(new Date().getFullYear(), language as Language)})-{new Date().getMonth() + 1}-{new Date().getDate()}
              </p>
            </div>
          </div>
        )}
      </div>

      {/* 常用費用管理 Modal */}
      {isFixedExpenseModalOpen && (
        <div className="fixed inset-0 z-[1000] flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-slate-900/60 dark:bg-slate-950/80 backdrop-blur-sm shadow-2xl"
            onClick={() => setIsFixedExpenseModalOpen(false)}
          />
          <div className="relative bg-white dark:bg-slate-900 rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-white/20 dark:border-slate-800">
            <div className="p-8 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/50">
              <div>
                <h3 className="text-2xl font-black text-slate-800 dark:text-slate-100 tracking-tight">
                  {language === 'zh-TW' ? '常用固定費用管理' : 'Fixed Expense Mgmt'}
                </h3>
                <p className="text-xs text-slate-400 dark:text-slate-500 font-bold uppercase tracking-widest mt-1">
                  Manage Frequent Payment Items (Rent, Utilities, Salary...)
                </p>
              </div>
              <button
                onClick={() => setIsFixedExpenseModalOpen(false)}
                className="w-10 h-10 flex items-center justify-center rounded-full bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-400 dark:text-slate-500 hover:text-rose-500 shadow-sm transition-all hover:rotate-90"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path d="M6 18L18 6M6 6l12 12" strokeWidth="2.5" strokeLinecap="round" />
                </svg>
              </button>
            </div>

            <div className="p-8 space-y-6">
              {/* 新增區 */}
              <div className="bg-emerald-50/50 dark:bg-emerald-900/10 p-6 rounded-2xl border border-emerald-100 dark:border-emerald-800/50 grid grid-cols-12 gap-3 items-end">
                <div className="col-span-12 mb-2">
                  <span className="text-[10px] font-black text-emerald-600 dark:text-emerald-400 uppercase tracking-widest">
                    {language === 'zh-TW' ? '新增常用項目' : 'Add Template'}
                  </span>
                </div>

                <div className="col-span-5 space-y-1.5">
                  <label className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase ml-1">
                    {language === 'zh-TW' ? '項目名稱' : 'Name'}
                  </label>
                  <input
                    value={newTemplate.name}
                    onChange={e => setNewTemplate({ ...newTemplate, name: e.target.value })}
                    placeholder={language === 'zh-TW' ? "例如: 每月辦公室租金..." : "Ex: Monthly Rent"}
                    className="w-full bg-white dark:bg-slate-800 border border-emerald-100 dark:border-emerald-900/50 rounded-xl px-4 py-2.5 text-sm font-bold text-slate-800 dark:text-slate-100 outline-none focus:ring-4 focus:ring-emerald-500/10"
                  />
                </div>

                <div className="col-span-3 space-y-1.5">
                  <label className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase ml-1">
                    {language === 'zh-TW' ? '金額 (TWD)' : 'Amount'}
                  </label>
                  <input
                    type="number"
                    value={newTemplate.amount}
                    onChange={e => setNewTemplate({ ...newTemplate, amount: Number(e.target.value) })}
                    className="w-full bg-white dark:bg-slate-800 border border-emerald-100 dark:border-emerald-900/50 rounded-xl px-4 py-2.5 text-sm font-black text-slate-800 dark:text-slate-100 outline-none focus:ring-4 focus:ring-emerald-500/10"
                  />
                </div>

                <div className="col-span-2 space-y-1.5">
                  <label className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase ml-1">
                    {language === 'zh-TW' ? '類別' : 'Cat'}
                  </label>
                  <select
                    value={newTemplate.category}
                    onChange={e => setNewTemplate({ ...newTemplate, category: e.target.value })}
                    className="w-full bg-white dark:bg-slate-800 border border-emerald-100 dark:border-emerald-900/50 rounded-xl px-3 py-2.5 text-sm font-bold text-slate-800 dark:text-slate-100 outline-none"
                  >
                    {categories.map(cat => (
                      <option key={cat.id} value={cat.name}>{cat.name}</option>
                    ))}
                    {categories.length === 0 && (
                      <option value="服務">{language === 'zh-TW' ? '服務' : 'Service'}</option>
                    )}
                  </select>
                </div>

                <div className="col-span-1">
                  <button
                    onClick={() => setIsManagingCategories(!isManagingCategories)}
                    className="w-full h-[41px] bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-400 rounded-xl flex items-center justify-center hover:bg-indigo-50 dark:hover:bg-indigo-900/30 hover:text-indigo-600 transition-all border border-slate-200 dark:border-slate-600"
                    title={language === 'zh-TW' ? "管理類別" : "Categories"}
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" strokeWidth="2" />
                      <path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" strokeWidth="2" />
                    </svg>
                  </button>
                </div>

                <div className="col-span-1">
                  <button
                    onClick={handleAddTemplate}
                    disabled={!newTemplate.name}
                    className="w-full bg-emerald-600 dark:bg-emerald-600 text-white rounded-xl py-2.5 text-sm font-black shadow-lg hover:bg-emerald-700 dark:hover:bg-emerald-500 disabled:opacity-50 transition-all flex items-center justify-center"
                  >
                    {language === 'zh-TW' ? '新增' : 'Add'}
                  </button>
                </div>
              </div>

              {/* 類別管理 */}
              {isManagingCategories && (
                <div className="bg-indigo-50/50 dark:bg-indigo-900/10 p-6 rounded-2xl border border-indigo-100 dark:border-indigo-800/50 space-y-4 animate-in slide-in-from-top-2">
                  <div className="flex justify-between items-center">
                    <span className="text-[10px] font-black text-indigo-600 dark:text-indigo-400 uppercase tracking-widest">
                      {language === 'zh-TW' ? '費用 / 收入類別清單管理' : 'Income / Categories Mgmt'}
                    </span>
                    <button
                      onClick={() => setIsManagingCategories(false)}
                      className="text-[10px] text-slate-400 dark:text-slate-500 font-bold hover:text-indigo-600 dark:hover:text-indigo-400"
                    >
                      {language === 'zh-TW' ? '完成關閉' : 'Close'}
                    </button>
                  </div>

                  <div className="flex gap-2">
                    <input
                      value={newCategoryName}
                      onChange={e => setNewCategoryName(e.target.value)}
                      placeholder={language === 'zh-TW' ? "輸入新類別名稱..." : "New category name..."}
                      className="flex-1 bg-white dark:bg-slate-800 border border-indigo-100 dark:border-indigo-900/50 rounded-xl px-4 py-2 text-xs font-bold text-slate-800 dark:text-slate-100 outline-none focus:ring-4 focus:ring-indigo-500/10"
                    />
                    <button
                      onClick={handleAddCategory}
                      className="bg-indigo-600 dark:bg-indigo-600 text-white px-4 py-2 rounded-xl text-xs font-black shadow-sm hover:bg-indigo-700 dark:hover:bg-indigo-500 transition-all"
                    >
                      {language === 'zh-TW' ? '新增類別' : 'Add'}
                    </button>
                  </div>

                  <div className="flex flex-wrap gap-2">
                    {categories.map(cat => (
                      <div
                        key={cat.id}
                        className="bg-white dark:bg-slate-800 border border-indigo-50 dark:border-slate-700 px-3 py-1.5 rounded-lg flex items-center gap-2 group transition-all hover:border-rose-200 dark:hover:border-rose-800"
                      >
                        <span className="text-[11px] font-bold text-slate-600 dark:text-slate-300">
                          {cat.name}
                        </span>
                        <button
                          onClick={() => handleDeleteCategory(cat.id)}
                          className="text-slate-300 dark:text-slate-600 hover:text-rose-500 dark:hover:text-rose-400 text-[10px]"
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 列表區 */}
              <div className="space-y-3 max-h-[400px] overflow-y-auto custom-scrollbar pr-2">
                <div className="flex justify-between items-center px-4">
                  <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">
                    {language === 'zh-TW' ? `已儲存範本 (${fixedTemplates.length})` : `Saved Templates (${fixedTemplates.length})`}
                  </span>
                </div>

                {fixedTemplates.map(t => (
                  <div
                    key={t.id}
                    className="group relative bg-white dark:bg-slate-800 border border-slate-100 dark:border-slate-700 p-5 rounded-2xl hover:border-indigo-100 dark:hover:border-indigo-900/50 hover:shadow-xl hover:shadow-indigo-500/5 transition-all flex justify-between items-center"
                  >
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 rounded-full bg-slate-50 dark:bg-slate-700 flex items-center justify-center text-slate-400 dark:text-slate-500 group-hover:bg-indigo-50 dark:group-hover:bg-indigo-900/30 group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      </div>
                      <div>
                        <p className="font-black text-slate-700 dark:text-slate-200 text-base">{t.name}</p>
                        <p className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest">{t.category}</p>
                      </div>
                    </div>

                    <div className="flex items-center gap-6">
                      <p className="text-xl font-black text-slate-900 dark:text-slate-100">
                        ${t.amount.toLocaleString()}
                      </p>
                      <button
                        onClick={() => handleDeleteTemplate(t.id)}
                        className="w-8 h-8 rounded-lg text-slate-400 dark:text-slate-500 hover:text-rose-500 dark:hover:text-rose-400 hover:bg-rose-50 dark:hover:bg-rose-900/30 flex items-center justify-center transition-all bg-slate-50 dark:bg-slate-800/50 border border-slate-100 dark:border-slate-700"
                        title={language === 'zh-TW' ? "刪除範本" : "Delete Template"}
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      </button>
                    </div>
                  </div>
                ))}

                {fixedTemplates.length === 0 && (
                  <div className="text-center py-10 bg-slate-50/50 dark:bg-slate-800/30 rounded-2xl border-2 border-dashed border-slate-100 dark:border-slate-800">
                    <p className="text-sm font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest">
                      {language === 'zh-TW' ? '目前尚無固定費用範本' : 'No templates found'}
                    </p>
                    <p className="text-[10px] text-slate-300 dark:text-slate-600 font-bold mt-1 tracking-widest">
                      ADD YOUR FIRST TEMPLATE ABOVE
                    </p>
                  </div>
                )}
              </div>
            </div>

            <div className="p-6 bg-slate-50 dark:bg-slate-800/50 text-center border-t border-slate-100 dark:border-slate-800">
              <p className="text-[10px] text-slate-400 dark:text-slate-500 font-bold">
                {language === 'zh-TW'
                  ? '範本將同步顯示於新增請款單對話框，方便快速選擇。'
                  : 'Templates will be available in the new request dialog.'}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};