import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
  FileSignature, Plus, Search, Send, Eye, X, Loader2,
  Clock, CheckCircle, XCircle, AlertCircle, Copy, RefreshCw, Ban,
  ExternalLink, ChevronDown, ChevronRight, User, Pencil, Trash2, Check, Printer,
  Download, FileArchive,
} from 'lucide-react';
import {
  useContracts,
  useContractTemplates,
  useCreateContract,
  useSendContract,
  useVoidContract,
  useResendContract,
  useCreateContractTemplate,
  useUpdateContractTemplate,
  useDeleteContractTemplate,
  useExportLegalPackage,
} from '../hooks/useContracts';
import { useCustomers } from '../hooks/useCustomers';
import apiClient from '../api/client';
import { Contract, ContractTemplate, Customer, ContractTemplateStatus, ContractScope } from '../types';

type ContractStatus = 'PENDING' | 'SIGNED' | 'EXPIRED' | 'VOIDED';

interface TemplateFormData {
  name: string;
  description: string;
  content: string;
  scope: ContractScope;
  status: ContractTemplateStatus;
  expires_after_days: number | null;
}

const Contracts: React.FC = () => {
  const { t } = useTranslation();

  // Section collapse state
  const [templatesExpanded, setTemplatesExpanded] = useState(true);
  const [contractsExpanded, setContractsExpanded] = useState(true);

  // Contract list state
  const [contractsTab, setContractsTab] = useState<ContractStatus | 'all'>('all');
  const [contractsSearch, setContractsSearch] = useState('');
  const [isCreateContractModalOpen, setIsCreateContractModalOpen] = useState(false);
  const [viewingContract, setViewingContract] = useState<Contract | null>(null);
  const [voidingContract, setVoidingContract] = useState<Contract | null>(null);
  const [voidReason, setVoidReason] = useState('');

  // Create contract form state
  const [selectedTemplateId, setSelectedTemplateId] = useState<string>('');
  const [selectedCustomerId, setSelectedCustomerId] = useState<string>('');
  const [selectedCustomerName, setSelectedCustomerName] = useState<string>('');
  const [customerSearchTerm, setCustomerSearchTerm] = useState('');
  const [isCustomerDropdownOpen, setIsCustomerDropdownOpen] = useState(false);
  const [sendEmailOnCreate, setSendEmailOnCreate] = useState(true);
  const customerDropdownRef = useRef<HTMLDivElement>(null);

  // Template state
  const [templatesTab, setTemplatesTab] = useState<ContractTemplateStatus | 'all'>('all');
  const [templatesSearch, setTemplatesSearch] = useState('');
  const [isTemplateModalOpen, setIsTemplateModalOpen] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<ContractTemplate | null>(null);
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const [templateFormData, setTemplateFormData] = useState<TemplateFormData>({
    name: '',
    description: '',
    content: '',
    scope: 'APPOINTMENT',
    status: 'DRAFT',
    expires_after_days: null,
  });

  // Data hooks
  const { data: contracts, isLoading: contractsLoading } = useContracts();
  const { data: allTemplates, isLoading: templatesLoading } = useContractTemplates();
  const { data: activeTemplates } = useContractTemplates('ACTIVE');
  const { data: customers = [], isLoading: customersLoading, error: customersError } = useCustomers();

  // Contract mutations
  const createContract = useCreateContract();
  const sendContract = useSendContract();
  const voidContract = useVoidContract();
  const resendContract = useResendContract();
  const exportLegalPackage = useExportLegalPackage();

  // Template mutations
  const createTemplate = useCreateContractTemplate();
  const updateTemplate = useUpdateContractTemplate();
  const deleteTemplate = useDeleteContractTemplate();

  // Filter customers based on search
  const filteredCustomers = useMemo(() => {
    if (!customers) return [];
    if (!customerSearchTerm) return customers;
    const term = customerSearchTerm.toLowerCase();
    return customers.filter(
      (c) => c.name?.toLowerCase().includes(term) || c.email?.toLowerCase().includes(term)
    );
  }, [customers, customerSearchTerm]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (customerDropdownRef.current && !customerDropdownRef.current.contains(event.target as Node)) {
        setIsCustomerDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Filter contracts
  const filteredContracts = useMemo(() => {
    if (!contracts) return [];
    return contracts.filter((contract) => {
      const matchesTab = contractsTab === 'all' || contract.status === contractsTab;
      const matchesSearch =
        contract.customer_name?.toLowerCase().includes(contractsSearch.toLowerCase()) ||
        contract.customer_email?.toLowerCase().includes(contractsSearch.toLowerCase()) ||
        contract.template_name?.toLowerCase().includes(contractsSearch.toLowerCase());
      return matchesTab && matchesSearch;
    });
  }, [contracts, contractsTab, contractsSearch]);

  // Count contracts by status
  const contractStatusCounts = useMemo(() => {
    if (!contracts) return { all: 0, PENDING: 0, SIGNED: 0, EXPIRED: 0, VOIDED: 0 };
    return {
      all: contracts.length,
      PENDING: contracts.filter((c) => c.status === 'PENDING').length,
      SIGNED: contracts.filter((c) => c.status === 'SIGNED').length,
      EXPIRED: contracts.filter((c) => c.status === 'EXPIRED').length,
      VOIDED: contracts.filter((c) => c.status === 'VOIDED').length,
    };
  }, [contracts]);

  // Filter templates
  const filteredTemplates = useMemo(() => {
    if (!allTemplates) return [];
    return allTemplates.filter((template) => {
      const matchesTab = templatesTab === 'all' || template.status === templatesTab;
      const matchesSearch = template.name.toLowerCase().includes(templatesSearch.toLowerCase()) ||
        template.description.toLowerCase().includes(templatesSearch.toLowerCase());
      return matchesTab && matchesSearch;
    });
  }, [allTemplates, templatesTab, templatesSearch]);

  // Count templates by status
  const templateStatusCounts = useMemo(() => {
    if (!allTemplates) return { all: 0, ACTIVE: 0, DRAFT: 0, ARCHIVED: 0 };
    return {
      all: allTemplates.length,
      ACTIVE: allTemplates.filter((t) => t.status === 'ACTIVE').length,
      DRAFT: allTemplates.filter((t) => t.status === 'DRAFT').length,
      ARCHIVED: allTemplates.filter((t) => t.status === 'ARCHIVED').length,
    };
  }, [allTemplates]);

  // Handlers
  const handleSelectCustomer = (customer: Customer) => {
    setSelectedCustomerId(customer.userId || customer.id);
    const displayName = customer.name || customer.email || `Customer #${customer.id}`;
    const displayEmail = customer.email || 'No email';
    setSelectedCustomerName(`${displayName} (${displayEmail})`);
    setCustomerSearchTerm('');
    setIsCustomerDropdownOpen(false);
  };

  const clearCustomerSelection = () => {
    setSelectedCustomerId('');
    setSelectedCustomerName('');
    setCustomerSearchTerm('');
  };

  const handleCreateContract = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedTemplateId || !selectedCustomerId) return;

    try {
      await createContract.mutateAsync({
        template: selectedTemplateId,
        customer_id: selectedCustomerId,
        send_email: sendEmailOnCreate,
      });

      setIsCreateContractModalOpen(false);
      setSelectedTemplateId('');
      setSelectedCustomerId('');
      setSelectedCustomerName('');
      setCustomerSearchTerm('');
      setSendEmailOnCreate(true);
    } catch (error) {
      console.error('Failed to create contract:', error);
    }
  };

  const handleSendContract = async (id: string) => {
    try {
      await sendContract.mutateAsync(id);
    } catch (error) {
      console.error('Failed to send contract:', error);
    }
  };

  const handleResendContract = async (id: string) => {
    try {
      await resendContract.mutateAsync(id);
    } catch (error) {
      console.error('Failed to resend contract:', error);
    }
  };

  const handleVoidContract = async () => {
    if (!voidingContract || !voidReason.trim()) return;

    try {
      await voidContract.mutateAsync({
        id: voidingContract.id,
        reason: voidReason,
      });
      setVoidingContract(null);
      setVoidReason('');
    } catch (error) {
      console.error('Failed to void contract:', error);
    }
  };

  const [copiedContractId, setCopiedContractId] = useState<string | null>(null);

  const copySigningLink = async (contract: Contract) => {
    if (!contract.public_token) {
      console.warn('No public_token found on contract:', contract);
      return;
    }

    const link = `${window.location.origin}/sign/${contract.public_token}`;

    // Helper to copy using fallback method
    const fallbackCopy = () => {
      const textArea = document.createElement('textarea');
      textArea.value = link;
      textArea.style.position = 'fixed';
      textArea.style.left = '-9999px';
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
    };

    // Use clipboard API if available (requires HTTPS), otherwise fallback
    if (navigator.clipboard?.writeText) {
      try {
        await navigator.clipboard.writeText(link);
      } catch {
        fallbackCopy();
      }
    } else {
      fallbackCopy();
    }

    setCopiedContractId(contract.id);
    setTimeout(() => setCopiedContractId(null), 2000);
  };

  // Template handlers
  const resetTemplateForm = () => {
    setTemplateFormData({
      name: '',
      description: '',
      content: '',
      scope: 'APPOINTMENT',
      status: 'DRAFT',
      expires_after_days: null,
    });
    setEditingTemplate(null);
  };

  const openCreateTemplateModal = () => {
    resetTemplateForm();
    setIsTemplateModalOpen(true);
  };

  const openEditTemplateModal = (template: ContractTemplate) => {
    setEditingTemplate(template);
    setTemplateFormData({
      name: template.name,
      description: template.description,
      content: template.content,
      scope: template.scope,
      status: template.status,
      expires_after_days: template.expires_after_days,
    });
    setIsTemplateModalOpen(true);
  };

  const handleTemplateSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingTemplate) {
        await updateTemplate.mutateAsync({
          id: editingTemplate.id,
          updates: templateFormData,
        });
      } else {
        await createTemplate.mutateAsync(templateFormData);
      }
      setIsTemplateModalOpen(false);
      resetTemplateForm();
    } catch (error) {
      console.error('Failed to save template:', error);
    }
  };

  const handleDeleteTemplate = async (id: string) => {
    try {
      await deleteTemplate.mutateAsync(id);
      setDeleteConfirmId(null);
    } catch (error) {
      console.error('Failed to delete template:', error);
    }
  };

  // Badge renderers
  const getContractStatusBadge = (status: string) => {
    const styles: Record<string, { bg: string; icon: React.ReactNode }> = {
      PENDING: { bg: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400', icon: <Clock size={14} /> },
      SIGNED: { bg: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400', icon: <CheckCircle size={14} /> },
      EXPIRED: { bg: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400', icon: <XCircle size={14} /> },
      VOIDED: { bg: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400', icon: <Ban size={14} /> },
    };
    const style = styles[status] || styles.PENDING;
    return (
      <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${style.bg}`}>
        {style.icon}
        {t(`contracts.status.${status.toLowerCase()}`)}
      </span>
    );
  };

  const getTemplateStatusBadge = (status: ContractTemplateStatus) => {
    const styles = {
      ACTIVE: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
      DRAFT: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
      ARCHIVED: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400',
    };
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[status]}`}>
        {t(`contracts.status.${status.toLowerCase()}`)}
      </span>
    );
  };

  const getScopeBadge = (scope: ContractScope) => {
    const styles = {
      CUSTOMER: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
      APPOINTMENT: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
    };
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[scope]}`}>
        {t(`contracts.scope.${scope.toLowerCase()}`)}
      </span>
    );
  };

  const formatDate = (dateString: string | null | undefined) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (contractsLoading && templatesLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  return (
    <div className="p-8 space-y-6">
      {/* Page Header */}
      <div className="mb-6">
        <div className="flex items-center gap-3 mb-2">
          <FileSignature className="w-8 h-8 text-blue-600" />
          <h1 className="text-3xl font-bold dark:text-white">{t('contracts.title')}</h1>
        </div>
        <p className="text-gray-600 dark:text-gray-400">{t('contracts.description')}</p>
      </div>

      {/* Templates Section */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
        <div className="w-full flex items-center justify-between p-4">
          <button
            onClick={() => setTemplatesExpanded(!templatesExpanded)}
            className="flex items-center gap-3 text-left hover:opacity-80 transition-opacity"
          >
            {templatesExpanded ? <ChevronDown size={20} /> : <ChevronRight size={20} />}
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
              {t('contracts.templates')}
            </h2>
            <span className="px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-sm">
              {allTemplates?.length || 0}
            </span>
          </button>
          <button
            onClick={() => openCreateTemplateModal()}
            className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
          >
            <Plus size={16} />
            {t('contracts.newTemplate')}
          </button>
        </div>

        {templatesExpanded && (
          <div className="border-t border-gray-200 dark:border-gray-700 p-4 space-y-4">
            {/* Template Search and Tabs */}
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="text"
                  value={templatesSearch}
                  onChange={(e) => setTemplatesSearch(e.target.value)}
                  placeholder={t('contracts.searchTemplates')}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white text-sm"
                />
              </div>
              <div className="flex gap-2">
                {(['all', 'ACTIVE', 'DRAFT', 'ARCHIVED'] as const).map((tab) => (
                  <button
                    key={tab}
                    onClick={() => setTemplatesTab(tab)}
                    className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                      templatesTab === tab
                        ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                        : 'text-gray-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700'
                    }`}
                  >
                    {tab === 'all' ? t('contracts.all') : t(`contracts.status.${tab.toLowerCase()}`)}
                    <span className="ml-1 text-xs">({templateStatusCounts[tab]})</span>
                  </button>
                ))}
              </div>
            </div>

            {/* Templates Table */}
            {filteredTemplates.length === 0 ? (
              <div className="py-8 text-center text-gray-500 dark:text-gray-400">
                <FileSignature className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
                <p>{templatesSearch ? t('contracts.noTemplatesSearch') : t('contracts.noTemplatesEmpty')}</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                  <thead>
                    <tr>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.template')}</th>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.scope')}</th>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.status')}</th>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.version')}</th>
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.actions')}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {filteredTemplates.map((template) => (
                      <tr key={template.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td className="px-4 py-3">
                          <div className="font-medium text-gray-900 dark:text-white">{template.name}</div>
                          {template.description && (
                            <div className="text-sm text-gray-500 dark:text-gray-400 truncate max-w-xs">{template.description}</div>
                          )}
                        </td>
                        <td className="px-4 py-3">{getScopeBadge(template.scope)}</td>
                        <td className="px-4 py-3">{getTemplateStatusBadge(template.status)}</td>
                        <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">v{template.version}</td>
                        <td className="px-4 py-3 text-right">
                          <div className="flex items-center justify-end gap-1">
                            <button
                              onClick={async () => {
                                try {
                                  const response = await apiClient.get(`/contracts/templates/${template.id}/preview_pdf/`, { responseType: 'blob' });
                                  const blob = new Blob([response.data], { type: 'application/pdf' });
                                  window.open(URL.createObjectURL(blob), '_blank');
                                } catch (error) {
                                  console.error('Failed to load PDF preview:', error);
                                  alert(t('contracts.actions.previewFailed'));
                                }
                              }}
                              className="p-1.5 text-gray-500 hover:text-blue-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
                              title={t('contracts.actions.preview')}
                            >
                              <Eye size={16} />
                            </button>
                            <button
                              onClick={() => openEditTemplateModal(template)}
                              className="p-1.5 text-gray-500 hover:text-blue-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
                              title={t('contracts.actions.edit')}
                            >
                              <Pencil size={16} />
                            </button>
                            <button
                              onClick={() => setDeleteConfirmId(template.id)}
                              className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
                              title={t('contracts.actions.delete')}
                            >
                              <Trash2 size={16} />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Contracts Section */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
        <div className="w-full flex items-center justify-between p-4">
          <button
            onClick={() => setContractsExpanded(!contractsExpanded)}
            className="flex items-center gap-3 text-left hover:opacity-80 transition-opacity"
          >
            {contractsExpanded ? <ChevronDown size={20} /> : <ChevronRight size={20} />}
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
              {t('contracts.sentContracts')}
            </h2>
            <span className="px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-sm">
              {contracts?.length || 0}
            </span>
          </button>
          <button
            onClick={() => setIsCreateContractModalOpen(true)}
            disabled={!activeTemplates || activeTemplates.length === 0}
            className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Plus size={16} />
            {t('contracts.actions.send')}
          </button>
        </div>

        {contractsExpanded && (
          <div className="border-t border-gray-200 dark:border-gray-700 p-4 space-y-4">
            {/* Contract Search and Tabs */}
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="text"
                  value={contractsSearch}
                  onChange={(e) => setContractsSearch(e.target.value)}
                  placeholder={t('contracts.searchContracts')}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white text-sm"
                />
              </div>
              <div className="flex gap-2 flex-wrap">
                {(['all', 'PENDING', 'SIGNED', 'EXPIRED', 'VOIDED'] as const).map((tab) => (
                  <button
                    key={tab}
                    onClick={() => setContractsTab(tab)}
                    className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                      contractsTab === tab
                        ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                        : 'text-gray-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700'
                    }`}
                  >
                    {tab === 'all' ? t('contracts.all') : t(`contracts.status.${tab.toLowerCase()}`)}
                    <span className="ml-1 text-xs">({contractStatusCounts[tab]})</span>
                  </button>
                ))}
              </div>
            </div>

            {/* Contracts Table */}
            {filteredContracts.length === 0 ? (
              <div className="py-8 text-center text-gray-500 dark:text-gray-400">
                <FileSignature className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
                <p>{contractsSearch ? t('contracts.noContractsSearch') : t('contracts.noContractsEmpty')}</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                  <thead>
                    <tr>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.customer')}</th>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.contract')}</th>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.status')}</th>
                      <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.created')}</th>
                      <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('contracts.table.actions')}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {filteredContracts.map((contract) => (
                      <tr key={contract.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td className="px-4 py-3">
                          <div className="font-medium text-gray-900 dark:text-white">{contract.customer_name || 'Unknown'}</div>
                          <div className="text-sm text-gray-500 dark:text-gray-400">{contract.customer_email}</div>
                        </td>
                        <td className="px-4 py-3">
                          <div className="font-medium text-gray-900 dark:text-white">{contract.template_name}</div>
                          {contract.sent_at && (
                            <div className="text-xs text-gray-500 dark:text-gray-400">{t('contracts.sentAt')}: {formatDate(contract.sent_at)}</div>
                          )}
                        </td>
                        <td className="px-4 py-3">
                          {getContractStatusBadge(contract.status)}
                          {contract.signed_at && (
                            <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">{t('contracts.signedAt')}: {formatDate(contract.signed_at)}</div>
                          )}
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{formatDate(contract.created_at)}</td>
                        <td className="px-4 py-3 text-right">
                          <div className="flex items-center justify-end gap-1">
                            <button onClick={() => setViewingContract(contract)} className="p-1.5 text-gray-500 hover:text-blue-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors" title={t('contracts.actions.viewDetails')}>
                              <Eye size={16} />
                            </button>
                            {contract.status === 'PENDING' && (
                              <>
                                <button onClick={() => copySigningLink(contract)} className={`p-1.5 rounded transition-colors ${copiedContractId === contract.id ? 'text-green-600 bg-green-100 dark:bg-green-900/30' : 'text-gray-500 hover:text-blue-600 hover:bg-gray-100 dark:hover:bg-gray-700'}`} title={copiedContractId === contract.id ? t('contracts.actions.copied') : t('contracts.actions.copyLink')}>
                                  {copiedContractId === contract.id ? <Check size={16} /> : <Copy size={16} />}
                                </button>
                                {!contract.sent_at ? (
                                  <button onClick={() => handleSendContract(contract.id)} disabled={sendContract.isPending} className="p-1.5 text-gray-500 hover:text-green-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors" title={t('contracts.actions.sendEmail')}>
                                    <Send size={16} />
                                  </button>
                                ) : (
                                  <button onClick={() => handleResendContract(contract.id)} disabled={resendContract.isPending} className="p-1.5 text-gray-500 hover:text-green-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors" title={t('contracts.actions.resend')}>
                                    <RefreshCw size={16} />
                                  </button>
                                )}
                                <button onClick={() => setVoidingContract(contract)} className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors" title={t('contracts.actions.void')}>
                                  <Ban size={16} />
                                </button>
                              </>
                            )}
                            {contract.public_token && contract.status === 'PENDING' && (
                              <a href={`/sign/${contract.public_token}`} target="_blank" rel="noopener noreferrer" className="p-1.5 text-gray-500 hover:text-blue-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors" title={t('contracts.actions.openSigningPage')}>
                                <ExternalLink size={16} />
                              </a>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Create Contract Modal */}
      {isCreateContractModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4" onClick={() => setIsCreateContractModalOpen(false)}>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('contracts.sendContract.title')}</h2>
              <button onClick={() => setIsCreateContractModalOpen(false)} className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleCreateContract} className="p-6 space-y-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.sendContract.selectTemplate')} *</label>
                <select value={selectedTemplateId} onChange={(e) => setSelectedTemplateId(e.target.value)} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white" required>
                  <option value="">{t('contracts.sendContract.selectTemplatePlaceholder')}</option>
                  {activeTemplates?.map((template) => (
                    <option key={template.id} value={template.id}>{template.name} (v{template.version})</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.sendContract.selectCustomer')} *</label>
                <div className="relative" ref={customerDropdownRef}>
                  {selectedCustomerId ? (
                    <div className="flex items-center gap-2 w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700">
                      <User size={16} className="text-gray-400" />
                      <span className="flex-1 text-gray-900 dark:text-white truncate">{selectedCustomerName}</span>
                      <button type="button" onClick={clearCustomerSelection} className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <X size={16} />
                      </button>
                    </div>
                  ) : (
                    <>
                      <div className="relative">
                        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                        <input type="text" value={customerSearchTerm} onChange={(e) => { setCustomerSearchTerm(e.target.value); setIsCustomerDropdownOpen(true); }} onFocus={() => setIsCustomerDropdownOpen(true)} placeholder={t('contracts.sendContract.searchCustomers')} className="w-full pl-10 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white" />
                        <ChevronDown size={16} className={`absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 transition-transform ${isCustomerDropdownOpen ? 'rotate-180' : ''}`} />
                      </div>
                      {isCustomerDropdownOpen && (
                        <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                          {customersLoading ? (
                            <div className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2">
                              <Loader2 size={14} className="animate-spin" />
                              {t('contracts.sendContract.loadingCustomers')}
                            </div>
                          ) : customersError ? (
                            <div className="px-4 py-3 text-sm text-red-500 dark:text-red-400">
                              {t('contracts.sendContract.loadCustomersFailed')}
                            </div>
                          ) : filteredCustomers.length === 0 ? (
                            <div className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
                              {customers.length === 0 ? t('contracts.sendContract.noCustomers') : t('contracts.sendContract.noMatchingCustomers')}
                            </div>
                          ) : (
                            filteredCustomers.map((customer) => (
                              <button key={customer.id} type="button" onClick={() => handleSelectCustomer(customer)} className="w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-3">
                                <div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0">
                                  <User size={14} className="text-blue-600 dark:text-blue-400" />
                                </div>
                                <div className="min-w-0 flex-1">
                                  <div className="font-medium text-gray-900 dark:text-white truncate">{customer.name || 'Unnamed'}</div>
                                  <div className="text-sm text-gray-500 dark:text-gray-400 truncate">{customer.email}</div>
                                </div>
                              </button>
                            ))
                          )}
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>
              <div className="flex items-center gap-3">
                <input type="checkbox" id="sendEmail" checked={sendEmailOnCreate} onChange={(e) => setSendEmailOnCreate(e.target.checked)} className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500" />
                <label htmlFor="sendEmail" className="text-sm text-gray-700 dark:text-gray-300">{t('contracts.sendContract.sendImmediately')}</label>
              </div>
              <div className="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button type="button" onClick={() => setIsCreateContractModalOpen(false)} className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">{t('common.cancel')}</button>
                <button type="submit" disabled={createContract.isPending || !selectedTemplateId || !selectedCustomerId} className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 flex items-center gap-2">
                  {createContract.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
                  {t('contracts.sendContract.send')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* View Contract Modal */}
      {viewingContract && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4" onClick={() => setViewingContract(null)}>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('contracts.contractDetails.title')}</h2>
              <button onClick={() => setViewingContract(null)} className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                <X size={20} />
              </button>
            </div>
            <div className="p-6 space-y-6">
              {/* Signed Contract Banner */}
              {viewingContract.status === 'SIGNED' && (
                <div className="p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
                  <div className="flex items-center gap-3">
                    <CheckCircle className="w-8 h-8 text-green-500 flex-shrink-0" />
                    <div>
                      <p className="font-semibold text-green-800 dark:text-green-300">{t('contracts.contractDetails.signedTitle')}</p>
                      <p className="text-sm text-green-700 dark:text-green-400">
                        {t('contracts.signedAt')}: {formatDate(viewingContract.signed_at)}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{t('contracts.contractDetails.customer')}</p>
                  <p className="font-medium text-gray-900 dark:text-white">{viewingContract.customer_name}</p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">{viewingContract.customer_email}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{t('contracts.contractDetails.template')}</p>
                  <p className="font-medium text-gray-900 dark:text-white">{viewingContract.template_name} (v{viewingContract.template_version})</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{t('contracts.contractDetails.status')}</p>
                  {getContractStatusBadge(viewingContract.status)}
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{t('contracts.contractDetails.created')}</p>
                  <p className="text-gray-900 dark:text-white">{formatDate(viewingContract.created_at)}</p>
                </div>
              </div>
              {viewingContract.content && (
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mb-2">{t('contracts.contractDetails.contentPreview')}</p>
                  <div className="prose dark:prose-invert max-w-none p-4 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-900 max-h-64 overflow-y-auto" dangerouslySetInnerHTML={{ __html: viewingContract.content }} />
                </div>
              )}

              {/* Action Buttons for Signed Contracts */}
              {viewingContract.status === 'SIGNED' && viewingContract.public_token && (
                <div className="flex flex-wrap gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                  <a
                    href={`/sign/${viewingContract.public_token}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    <Eye size={18} />
                    {t('contracts.contractDetails.viewFullContract')}
                  </a>
                  <button
                    onClick={() => {
                      const url = `/sign/${viewingContract.public_token}`;
                      const printWindow = window.open(url, '_blank');
                      if (printWindow) {
                        printWindow.onload = () => {
                          setTimeout(() => printWindow.print(), 500);
                        };
                      }
                    }}
                    className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                  >
                    <Printer size={18} />
                    {t('contracts.contractDetails.printContract')}
                  </button>
                  <button
                    onClick={() => exportLegalPackage.mutate(viewingContract.id)}
                    disabled={exportLegalPackage.isPending}
                    className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50"
                  >
                    {exportLegalPackage.isPending ? (
                      <Loader2 size={18} className="animate-spin" />
                    ) : (
                      <FileArchive size={18} />
                    )}
                    {t('contracts.contractDetails.exportLegal')}
                  </button>
                </div>
              )}

              {/* Signing Link for Pending Contracts */}
              {viewingContract.public_token && viewingContract.status === 'PENDING' && (
                <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                  <p className="text-sm font-medium text-blue-700 dark:text-blue-300 mb-2">{t('contracts.contractDetails.signingLink')}</p>
                  <div className="flex items-center gap-2">
                    <input type="text" readOnly value={`${window.location.origin}/sign/${viewingContract.public_token}`} className="flex-1 px-3 py-2 text-sm bg-white dark:bg-gray-800 border border-blue-200 dark:border-blue-700 rounded" />
                    <button onClick={() => copySigningLink(viewingContract)} className={`px-3 py-2 rounded transition-colors ${copiedContractId === viewingContract.id ? 'bg-green-600 text-white' : 'bg-blue-600 text-white hover:bg-blue-700'}`}>
                      {copiedContractId === viewingContract.id ? <Check size={16} /> : <Copy size={16} />}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Void Contract Modal */}
      {voidingContract && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4" onClick={() => setVoidingContract(null)}>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <Ban className="w-5 h-5 text-red-600 dark:text-red-400" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">{t('contracts.voidContract.title')}</h3>
            </div>
            <p className="text-gray-600 dark:text-gray-400 mb-4">{t('contracts.voidContract.description')}</p>
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.voidContract.reason')} *</label>
              <textarea value={voidReason} onChange={(e) => setVoidReason(e.target.value)} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent dark:bg-gray-700 dark:text-white" rows={3} placeholder={t('contracts.voidContract.reasonPlaceholder')} required />
            </div>
            <div className="flex justify-end gap-3">
              <button onClick={() => { setVoidingContract(null); setVoidReason(''); }} className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">{t('common.cancel')}</button>
              <button onClick={handleVoidContract} disabled={voidContract.isPending || !voidReason.trim()} className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 flex items-center gap-2">
                {voidContract.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
                {t('contracts.voidContract.confirm')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Create/Edit Template Modal */}
      {isTemplateModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4" onClick={() => setIsTemplateModalOpen(false)}>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{editingTemplate ? t('contracts.editTemplate') : t('contracts.createTemplate')}</h2>
              <button onClick={() => setIsTemplateModalOpen(false)} className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleTemplateSubmit} className="p-6 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.templateName')} *</label>
                  <input type="text" value={templateFormData.name} onChange={(e) => setTemplateFormData({ ...templateFormData, name: e.target.value })} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white" required />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.scope.label')} *</label>
                  <select value={templateFormData.scope} onChange={(e) => setTemplateFormData({ ...templateFormData, scope: e.target.value as ContractScope })} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white">
                    <option value="APPOINTMENT">{t('contracts.scope.appointment')} ({t('contracts.scope.appointmentDesc')})</option>
                    <option value="CUSTOMER">{t('contracts.scope.customer')} ({t('contracts.scope.customerDesc')})</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.status.label')}</label>
                  <select value={templateFormData.status} onChange={(e) => setTemplateFormData({ ...templateFormData, status: e.target.value as ContractTemplateStatus })} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white">
                    <option value="DRAFT">{t('contracts.status.draft')}</option>
                    <option value="ACTIVE">{t('contracts.status.active')}</option>
                    <option value="ARCHIVED">{t('contracts.status.archived')}</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.expiresAfterDays')}</label>
                  <input type="number" value={templateFormData.expires_after_days || ''} onChange={(e) => setTemplateFormData({ ...templateFormData, expires_after_days: e.target.value ? parseInt(e.target.value) : null })} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white" placeholder={t('contracts.expiresAfterDaysHint')} min="1" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.templateDescription')}</label>
                <input type="text" value={templateFormData.description} onChange={(e) => setTemplateFormData({ ...templateFormData, description: e.target.value })} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white" placeholder={t('contracts.templateDescription')} />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('contracts.contentHtml')} *</label>
                <div className="mb-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                  <p className="text-sm text-blue-700 dark:text-blue-300 mb-2"><strong>{t('contracts.availableVariables')}:</strong></p>
                  <div className="flex flex-wrap gap-2 text-xs font-mono">
                    {['{{CUSTOMER_NAME}}', '{{CUSTOMER_EMAIL}}', '{{BUSINESS_NAME}}', '{{DATE}}', '{{YEAR}}'].map((v) => (
                      <span key={v} className="px-2 py-1 bg-white dark:bg-gray-700 rounded cursor-pointer hover:bg-blue-100 dark:hover:bg-blue-800" onClick={() => setTemplateFormData({ ...templateFormData, content: templateFormData.content + v })}>{v}</span>
                    ))}
                  </div>
                </div>
                <textarea value={templateFormData.content} onChange={(e) => setTemplateFormData({ ...templateFormData, content: e.target.value })} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white font-mono text-sm" rows={12} required placeholder="<h1>Service Agreement</h1>&#10;<p>This agreement is between {{BUSINESS_NAME}} and {{CUSTOMER_NAME}}...</p>" />
              </div>
              <div className="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button type="button" onClick={() => setIsTemplateModalOpen(false)} className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">{t('common.cancel')}</button>
                <button type="submit" disabled={createTemplate.isPending || updateTemplate.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 flex items-center gap-2">
                  {(createTemplate.isPending || updateTemplate.isPending) && <Loader2 className="w-4 h-4 animate-spin" />}
                  {editingTemplate ? t('contracts.actions.saveChanges') : t('contracts.createTemplate')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Template Confirmation Modal */}
      {deleteConfirmId && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4" onClick={() => setDeleteConfirmId(null)}>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">{t('contracts.deleteTemplate.title')}</h3>
            </div>
            <p className="text-gray-600 dark:text-gray-400 mb-6">{t('contracts.deleteTemplate.description')}</p>
            <div className="flex justify-end gap-3">
              <button onClick={() => setDeleteConfirmId(null)} className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">{t('common.cancel')}</button>
              <button onClick={() => handleDeleteTemplate(deleteConfirmId)} disabled={deleteTemplate.isPending} className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 flex items-center gap-2">
                {deleteTemplate.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
                {t('contracts.deleteTemplate.confirm')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Contracts;
