'use client'

import { useState, useEffect, useCallback } from 'react'
import ProtectedRoute from '@/components/ProtectedRoute'
import Modal from '@/components/Modal'
import LoadingSpinner from '@/components/LoadingSpinner'
import Link from 'next/link'
import { toast } from 'react-hot-toast'
import {
  FileText,
  Plus,
  Search,
  AlertCircle,
  ArrowLeft,
  Eye,
  Loader2,
  Edit,
  Trash2,
} from 'lucide-react'
import { useAuth } from '@/contexts/AuthContext'
import { tendersAPI, Tender, CreateTenderData, TenderFilters } from '@/lib/api/tenders'
import { useLanguage } from '@/contexts/LanguageContext'

const SOURCE_LABELS: Record<string, string> = {
  GOVERNMENT_SITE: 'Government site',
  OFFICIAL_GAZETTE: 'Official gazette',
  PERSONAL: 'Personal relations',
  PARTNER: 'Partner companies',
  WHATSAPP_TELEGRAM: 'WhatsApp/Telegram',
  PORTAL: 'Tender portals',
  EMAIL: 'Email',
  MANUAL: 'Manual entry',
}

const SYRIA_PROVINCES = [
  'دمشق',
  'ريف دمشق',
  'حلب',
  'حمص',
  'حماة',
  'اللاذقية',
  'طرطوس',
  'إدلب',
  'درعا',
  'السويداء',
  'القنيطرة',
  'دير الزور',
  'الرقة',
  'الحسكة',
]

const ANNOUNCEMENT_LABELS: Record<string, string> = {
  FIRST: 'First announcement',
  RE_ANNOUNCEMENT_2: 'Re-announcement 2nd',
  RE_ANNOUNCEMENT_3: 'Re-announcement 3rd',
  RE_ANNOUNCEMENT_4: 'Re-announcement 4th',
}

const getInitialFormData = (): CreateTenderData => ({
  tenderNumber: '',
  issueNumber: '',
  issuingBodyName: '',
  title: '',
  termsValue: 0,
  bondValue: 0,
  initialBondValue: 0,
  finalBondValue: 0,
  finalBondRefundPeriod: '',
  siteVisitRequired: false,
  siteVisitLocation: '',
  termsPickupProvince: '',
  announcementDate: '',
  closingDate: '',
  source: 'MANUAL',
  announcementType: 'FIRST',
  notes: '',
})

function TendersContent() {
  const { t } = useLanguage()
  const { hasPermission } = useAuth()

  const [tenders, setTenders] = useState<Tender[]>([])
  const [loading, setLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 10
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [showCreateModal, setShowCreateModal] = useState(false)

  const [formData, setFormData] = useState<CreateTenderData>(getInitialFormData())
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)
  const [possibleDuplicates, setPossibleDuplicates] = useState<Tender[]>([])
  const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
  const [sourceValues, setSourceValues] = useState<string[]>([])
  const [announcementTypeValues, setAnnouncementTypeValues] = useState<string[]>([])
  const [showEditModal, setShowEditModal] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [selectedTender, setSelectedTender] = useState<Tender | null>(null)

  const canCreateTender = hasPermission('tenders', 'create')
  const canViewTender = hasPermission('tenders', 'view')
  const canEditTender = hasPermission('tenders', 'edit')
  const canDeleteTender = hasPermission('tenders', 'delete')

  const resetForm = () => {
    setFormData(getInitialFormData())
    setFormErrors({})
    setPossibleDuplicates([])
    setShowDuplicateWarning(false)
  }

  const fillFormFromTender = (tender: Tender): CreateTenderData => ({
    tenderNumber: tender.tenderNumber || '',
    issueNumber: tender.issueNumber || '',
    issuingBodyName: tender.issuingBodyName || '',
    title: tender.title || '',
    termsValue: Number(tender.termsValue || 0),
    bondValue: Number(tender.bondValue || 0),
    initialBondValue: Number(tender.initialBondValue ?? tender.bondValue ?? 0),
    finalBondValue: tender.finalBondValue != null ? Number(tender.finalBondValue) : 0,
    finalBondRefundPeriod: tender.finalBondRefundPeriod || '',
    siteVisitRequired: !!tender.siteVisitRequired,
    siteVisitLocation: tender.siteVisitLocation || '',
    termsPickupProvince: tender.termsPickupProvince || '',
    announcementDate: tender.announcementDate?.split('T')[0] || '',
    closingDate: tender.closingDate?.split('T')[0] || '',
    announcementLink: tender.announcementLink || '',
    source: tender.source || 'MANUAL',
    sourceOther: tender.sourceOther || '',
    announcementType: tender.announcementType || 'FIRST',
    notes: tender.notes || '',
    contactId: tender.contactId || '',
  })

  const openEditModal = (tender: Tender) => {
    setSelectedTender(tender)
    setFormData(fillFormFromTender(tender))
    setFormErrors({})
    setPossibleDuplicates([])
    setShowDuplicateWarning(false)
    setShowEditModal(true)
  }

  const openDeleteDialog = (tender: Tender) => {
    setSelectedTender(tender)
    setShowDeleteDialog(true)
  }

  const fetchTenders = useCallback(async () => {
    setLoading(true)
    try {
      const filters: TenderFilters = { page: currentPage, pageSize }
      if (searchTerm) filters.search = searchTerm
      if (selectedStatus !== 'all') filters.status = selectedStatus

      const data = await tendersAPI.getAll(filters)
      setTenders(data.tenders)
      setTotal(data.total)
      setTotalPages(data.totalPages)
    } catch {
      toast.error(t('tenders.loadError') || 'Failed to load tenders')
    } finally {
      setLoading(false)
    }
  }, [currentPage, searchTerm, selectedStatus, t])

  useEffect(() => {
    fetchTenders()
  }, [fetchTenders])

  useEffect(() => {
    tendersAPI.getSourceValues().then(setSourceValues).catch(() => {})
    tendersAPI.getAnnouncementTypeValues().then(setAnnouncementTypeValues).catch(() => {})
  }, [])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()

    const errors: Record<string, string> = {}

    if (!formData.issuingBodyName?.trim()) errors.issuingBodyName = t('common.required')
    if (!formData.title?.trim()) errors.title = t('common.required')

    if (Number(formData.initialBondValue || 0) < 0) {
      errors.initialBondValue = t('common.required')
    }

    if (formData.siteVisitRequired && !formData.siteVisitLocation?.trim()) {
      errors.siteVisitLocation = t('common.required')
    }

    setFormErrors(errors)
    if (Object.keys(errors).length > 0) return

    setSubmitting(true)
    try {
      const result = await tendersAPI.create({
        ...formData,
        bondValue: Number(formData.initialBondValue ?? formData.bondValue ?? 0),
      })

      if (result.possibleDuplicates && result.possibleDuplicates.length > 0) {
        setPossibleDuplicates(result.possibleDuplicates)
        setShowDuplicateWarning(true)
        toast(t('tenders.duplicateWarning') || 'Possible duplicates found. Please review.', {
          icon: '⚠️',
        })
      } else {
        toast.success(t('tenders.createSuccess') || 'Tender created successfully')
        setShowCreateModal(false)
        resetForm()
        fetchTenders()
      }
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to create tender')
    } finally {
      setSubmitting(false)
    }
  }

  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedTender) return

    const errors: Record<string, string> = {}

    if (!formData.issuingBodyName?.trim()) errors.issuingBodyName = t('common.required')
    if (!formData.title?.trim()) errors.title = t('common.required')

    if (Number(formData.initialBondValue || 0) < 0) {
      errors.initialBondValue = t('common.required')
    }

    if (formData.siteVisitRequired && !formData.siteVisitLocation?.trim()) {
      errors.siteVisitLocation = t('common.required')
    }

    setFormErrors(errors)
    if (Object.keys(errors).length > 0) return

    setSubmitting(true)
    try {
      await tendersAPI.update(selectedTender.id, {
        ...formData,
        bondValue: Number(formData.initialBondValue ?? formData.bondValue ?? 0),
      })

      toast.success(t('tenders.updateSuccess') || 'Tender updated successfully')
      setShowEditModal(false)
      setSelectedTender(null)
      resetForm()
      fetchTenders()
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to update tender')
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async () => {
    if (!selectedTender) return

    setSubmitting(true)
    try {
      await tendersAPI.delete(selectedTender.id)
      toast.success(t('tenders.deleteSuccess') || 'Tender deleted successfully')
      setShowDeleteDialog(false)
      setSelectedTender(null)
      fetchTenders()
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to delete tender')
    } finally {
      setSubmitting(false)
    }
  }

  const renderTenderForm = (mode: 'create' | 'edit') => (
    <form onSubmit={mode === 'create' ? handleCreate : handleEdit} className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t('tenders.tenderNumber')}
          </label>
          <input
            type="text"
            value={formData.tenderNumber ?? ''}
            onChange={(e) => setFormData({ ...formData, tenderNumber: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          />
          {formErrors.tenderNumber && (
            <p className="text-red-500 text-xs mt-1">{formErrors.tenderNumber}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t('tenders.issuingBody')} *
          </label>
          <input
            type="text"
            value={formData.issuingBodyName}
            onChange={(e) => setFormData({ ...formData, issuingBodyName: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          />
          {formErrors.issuingBodyName && (
            <p className="text-red-500 text-xs mt-1">{formErrors.issuingBodyName}</p>
          )}
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          رقم العدد
        </label>
        <input
          type="text"
          value={formData.issueNumber || ''}
          onChange={(e) => setFormData({ ...formData, issueNumber: e.target.value })}
          className="w-full px-3 py-2 border rounded-lg"
          placeholder="رقم العدد (اختياري)"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          {t('tenders.titleLabel')} *
        </label>
        <input
          type="text"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          className="w-full px-3 py-2 border rounded-lg"
        />
        {formErrors.title && (
          <p className="text-red-500 text-xs mt-1">{formErrors.title}</p>
        )}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            قيمة دفتر الشروط *
          </label>
          <input
            type="number"
            min={0}
            value={formData.termsValue ?? ''}
            onChange={(e) =>
              setFormData({
                ...formData,
                termsValue: e.target.value === '' ? 0 : Number(e.target.value),
              })
            }
            className="w-full px-3 py-2 border rounded-lg"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            قيمة التأمينات الأولية *
          </label>
          <input
            type="number"
            min={0}
            value={formData.initialBondValue ?? ''}
            onChange={(e) => {
              const v = e.target.value === '' ? 0 : Number(e.target.value)
              setFormData({ ...formData, initialBondValue: v, bondValue: v })
            }}
            className="w-full px-3 py-2 border rounded-lg"
          />
          {formErrors.initialBondValue && (
            <p className="text-red-500 text-xs mt-1">{formErrors.initialBondValue}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            قيمة التأمينات النهائية
          </label>
          <input
            type="number"
            min={0}
            value={formData.finalBondValue ?? ''}
            onChange={(e) =>
              setFormData({
                ...formData,
                finalBondValue: e.target.value === '' ? 0 : Number(e.target.value),
              })
            }
            className="w-full px-3 py-2 border rounded-lg"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            زمن الاسترجاع
          </label>
          <input
            type="text"
            value={formData.finalBondRefundPeriod || ''}
            onChange={(e) =>
              setFormData({ ...formData, finalBondRefundPeriod: e.target.value })
            }
            placeholder="مثال: بعد 90 يوم من التسليم النهائي"
            className="w-full px-3 py-2 border rounded-lg"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t('tenders.announcementDate')}
          </label>
          <input
            type="date"
            value={formData.announcementDate ?? ''}
            onChange={(e) => setFormData({ ...formData, announcementDate: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          />
          {formErrors.announcementDate && (
            <p className="text-red-500 text-xs mt-1">{formErrors.announcementDate}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t('tenders.closingDate')}
          </label>
          <input
            type="date"
            value={formData.closingDate ?? ''}
            onChange={(e) => setFormData({ ...formData, closingDate: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          />
          {formErrors.closingDate && (
            <p className="text-red-500 text-xs mt-1">{formErrors.closingDate}</p>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t('tenders.source')}
          </label>
          <select
            value={formData.source}
            onChange={(e) => setFormData({ ...formData, source: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          >
            {(sourceValues.length > 0 ? sourceValues : Object.keys(SOURCE_LABELS)).map((s) => (
              <option key={s} value={s}>
                {SOURCE_LABELS[s] || s}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t('tenders.announcementType')}
          </label>
          <select
            value={formData.announcementType}
            onChange={(e) => setFormData({ ...formData, announcementType: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          >
            {(announcementTypeValues.length > 0
              ? announcementTypeValues
              : Object.keys(ANNOUNCEMENT_LABELS)
            ).map((a) => (
              <option key={a} value={a}>
                {ANNOUNCEMENT_LABELS[a] || a}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            زيارة الموقع
          </label>
          <select
            value={formData.siteVisitRequired ? 'YES' : 'NO'}
            onChange={(e) =>
              setFormData({
                ...formData,
                siteVisitRequired: e.target.value === 'YES',
                siteVisitLocation: e.target.value === 'YES' ? formData.siteVisitLocation || '' : '',
              })
            }
            className="w-full px-3 py-2 border rounded-lg"
          >
            <option value="NO">غير إجبارية</option>
            <option value="YES">إجبارية</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            مكان استلام دفتر الشروط - المحافظة
          </label>
          <select
            value={formData.termsPickupProvince || ''}
            onChange={(e) => setFormData({ ...formData, termsPickupProvince: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
          >
            <option value="">اختر المحافظة</option>
            {SYRIA_PROVINCES.map((province) => (
              <option key={province} value={province}>
                {province}
              </option>
            ))}
          </select>
        </div>
      </div>

      {formData.siteVisitRequired && (
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            مكان الزيارة *
          </label>
          <input
            type="text"
            value={formData.siteVisitLocation || ''}
            onChange={(e) => setFormData({ ...formData, siteVisitLocation: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg"
            placeholder="اكتب مكان أو عنوان زيارة الموقع"
          />
          {formErrors.siteVisitLocation && (
            <p className="text-red-500 text-xs mt-1">{formErrors.siteVisitLocation}</p>
          )}
        </div>
      )}

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          {t('tenders.announcementLink')}
        </label>
        <input
          type="url"
          value={formData.announcementLink || ''}
          onChange={(e) => setFormData({ ...formData, announcementLink: e.target.value })}
          className="w-full px-3 py-2 border rounded-lg"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          {t('common.notes')}
        </label>
        <textarea
          value={formData.notes || ''}
          onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
          className="w-full px-3 py-2 border rounded-lg"
          rows={2}
        />
      </div>

      {mode === 'create' && showDuplicateWarning && possibleDuplicates.length > 0 && (
        <div className="p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-start gap-2">
          <AlertCircle className="h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-medium text-amber-800">
              {t('tenders.duplicateWarning') || 'Possible duplicates found'}
            </p>
            <ul className="text-sm text-amber-700 mt-1 list-disc list-inside">
              {possibleDuplicates.slice(0, 3).map((d) => (
                <li key={d.id}>
                  <Link href={`/tenders/${d.id}`} className="underline">
                    {d.tenderNumber} - {d.title}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        </div>
      )}

      <div className="flex justify-end gap-2 pt-4">
        <button
          type="button"
          onClick={() => {
            if (mode === 'create') {
              setShowCreateModal(false)
            } else {
              setShowEditModal(false)
              setSelectedTender(null)
            }
            resetForm()
          }}
          className="px-4 py-2 border rounded-lg"
          disabled={submitting}
        >
          {t('common.cancel')}
        </button>

        <button
          type="submit"
          disabled={submitting}
          className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 flex items-center gap-2"
        >
          {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
          {mode === 'create' ? t('common.save') : (t('common.save') || 'Save')}
        </button>
      </div>
    </form>
  )

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Link
              href="/dashboard"
              className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
            >
              <ArrowLeft className="h-5 w-5" />
            </Link>

            <div className="flex items-center gap-2">
              <FileText className="h-8 w-8 text-indigo-600" />
              <div>
                <h1 className="text-2xl font-bold text-gray-900">
                  {t('nav.tenders') || 'Tenders'}
                </h1>
                <p className="text-sm text-gray-600">
                  {t('tenders.subtitle') || 'Tender Management'}
                </p>
              </div>
            </div>
          </div>

          {canCreateTender && (
            <button
              onClick={() => {
                resetForm()
                setShowCreateModal(true)
              }}
              className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
            >
              <Plus className="h-5 w-5" />
              {t('tenders.addTender') || 'Add Tender'}
            </button>
          )}
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <div className="p-4 border-b border-gray-200 flex flex-wrap gap-4 items-center">
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
              <input
                type="text"
                placeholder={t('tenders.searchPlaceholder') || 'Search by number, title, issuing body...'}
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
            </div>

            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"
            >
              <option value="all">{t('common.all') || 'All status'}</option>
              <option value="ACTIVE">Active</option>
              <option value="EXPIRED">Expired</option>
              <option value="CONVERTED_TO_DEAL">Converted</option>
              <option value="CANCELLED">Cancelled</option>
            </select>
          </div>

          {loading ? (
            <div className="flex justify-center py-12">
              <LoadingSpinner />
            </div>
          ) : tenders.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              {t('tenders.noTenders') || 'No tenders found.'}
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      {t('tenders.tenderNumber') || 'Number'}
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      رقم العدد
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      {t('tenders.title') || 'Title'}
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      {t('tenders.issuingBody') || 'Issuing body'}
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      {t('tenders.closingDate') || 'Closing date'}
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      {t('common.status')}
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                      {t('common.actions')}
                    </th>
                  </tr>
                </thead>

                <tbody className="bg-white divide-y divide-gray-200">
                  {tenders.map((tender) => (
                    <tr key={tender.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 text-sm font-semibold text-gray-900 text-right align-middle">
                        {tender.tenderNumber}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-700 text-right align-middle">
                        {tender.issueNumber || '-'}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-900 text-right align-middle">
                        {tender.title}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-600 text-right align-middle">
                        {tender.issuingBodyName}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-600 text-right align-middle">
                        {tender.closingDate?.split('T')[0]}
                      </td>
                      <td className="px-6 py-4 text-right align-middle">
                        <span
                          className={`inline-flex px-2.5 py-1 text-xs font-medium rounded-full ${
                            tender.status === 'ACTIVE'
                              ? 'bg-green-100 text-green-800'
                              : tender.status === 'EXPIRED'
                                ? 'bg-red-100 text-red-800'
                                : tender.status === 'CONVERTED_TO_DEAL'
                                  ? 'bg-blue-100 text-blue-800'
                                  : 'bg-gray-100 text-gray-800'
                          }`}
                        >
                          {tender.status === 'EXPIRED' ? 'EXPIRED' : tender.status}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-right align-middle">
                        <div className="flex items-center justify-end gap-3">
                          {canViewTender && (
                            <Link
                              href={`/tenders/${tender.id}`}
                              className="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-md transition-colors"
                              title={t('common.view') || 'View'}
                            >
                              <Eye className="h-4 w-4" />
                            </Link>
                          )}

                          {canEditTender && (
                            <button
                              type="button"
                              onClick={() => openEditModal(tender)}
                              className="p-1.5 text-green-600 hover:bg-green-50 rounded-md transition-colors"
                              title={t('common.edit') || 'Edit'}
                            >
                              <Edit className="h-4 w-4" />
                            </button>
                          )}

                          {canDeleteTender && (
                            <button
                              type="button"
                              onClick={() => openDeleteDialog(tender)}
                              className="p-1.5 text-red-600 hover:bg-red-50 rounded-md transition-colors"
                              title={t('common.delete') || 'Delete'}
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>

                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {totalPages > 1 && (
            <div className="px-4 py-3 border-t border-gray-200 flex items-center justify-between">
              <p className="text-sm text-gray-600">
                {t('common.showing') || 'Showing'} {(currentPage - 1) * pageSize + 1}–
                {Math.min(currentPage * pageSize, total)} {t('common.of') || 'of'} {total}
              </p>
              <div className="flex gap-2">
                <button
                  disabled={currentPage <= 1}
                  onClick={() => setCurrentPage((p) => p - 1)}
                  className="px-3 py-1 border rounded disabled:opacity-50"
                >
                  {t('crm.paginationPrevious') || 'Previous'}
                </button>
                <button
                  disabled={currentPage >= totalPages}
                  onClick={() => setCurrentPage((p) => p + 1)}
                  className="px-3 py-1 border rounded disabled:opacity-50"
                >
                  {t('crm.paginationNext') || 'Next'}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      <Modal
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false)
          resetForm()
        }}
        title={t('tenders.addTender') || 'Add Tender'}
      >
        {renderTenderForm('create')}
      </Modal>

      <Modal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false)
          setSelectedTender(null)
          resetForm()
        }}
        title={t('common.edit') || 'Edit Tender'}
      >
        {renderTenderForm('edit')}
      </Modal>

      {showDeleteDialog && selectedTender && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div
            className="fixed inset-0 bg-black bg-opacity-50"
            onClick={() => {
              setShowDeleteDialog(false)
              setSelectedTender(null)
            }}
          />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <div className="flex items-center gap-4 mb-4">
                <div className="bg-red-100 p-3 rounded-full">
                  <Trash2 className="h-6 w-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">
                    {t('common.delete') || 'Delete Tender'}
                  </h3>
                  <p className="text-sm text-gray-600">This action cannot be undone</p>
                </div>
              </div>

              <p className="text-gray-700 mb-6">
                Are you sure you want to delete tender{' '}
                <span className="font-semibold">{selectedTender.tenderNumber}</span>?
              </p>

              <div className="flex items-center justify-end gap-3">
                <button
                  onClick={() => {
                    setShowDeleteDialog(false)
                    setSelectedTender(null)
                  }}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                  disabled={submitting}
                >
                  {t('common.cancel') || 'Cancel'}
                </button>
                <button
                  onClick={handleDelete}
                  className="inline-flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
                  disabled={submitting}
                >
                  {submitting ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Deleting...
                    </>
                  ) : (
                    t('common.delete') || 'Delete'
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default function TendersPage() {
  return (
    <ProtectedRoute>
      <TendersContent />
    </ProtectedRoute>
  )
}