"use client"

import { useState, useEffect, useCallback } from 'react'
import { motion } from 'framer-motion'
import { 
  Search, FileText, CheckCircle, 
  ChevronRight, Building2, Users, RefreshCw, Loader2, Download, X, Globe, Briefcase, Plus, Clock, Send, AlertTriangle
} from 'lucide-react'
import CustomSelect from '@/components/ui/custom-select'
import { getSupabaseClient } from '@/lib/supabase/client'
import { useAuth } from '@/lib/auth/AuthProvider'
import { useVisibilityRefresh } from '@/lib/hooks/useVisibilityRefresh'

interface QuoteRequest {
  id: string
  company_name: string
  authorized_person: string
  email: string
  phone: string
  employee_count: number
  tehlike_sinifi: string | null
  nace_code: string | null
  city: string | null
  requested_services: string[] | null
  notes: string | null
  hekim_suresi: number | null
  uzman_suresi: number | null
  dsp_suresi: number | null
  status: string
  source: string | null
  created_at: string
}

interface ServiceType {
  id: string
  name: string
}

interface ServicePrice {
  id: string
  name: string
  price: string
}

interface Company {
  id: string
  company_name: string
  email: string
  employee_count: number | null
  tehlike_sinifi: string | null
}

const statusConfig = {
  pending: { label: 'Bekliyor', color: 'amber' },
  quoted: { label: 'Teklif Gönderildi', color: 'blue' },
  reviewing: { label: 'Şirket İnceliyor', color: 'purple' },
  accepted: { label: 'Şirket Onayladı', color: 'green' },
  rejected: { label: 'Şirket Reddetti', color: 'red' },
  expired: { label: 'Süresi Doldu', color: 'gray' },
}

// Status grupları
const pendingStatuses = ['pending']
const sentStatuses = ['quoted', 'reviewing', 'accepted', 'rejected', 'expired']

const tehlikeConfig: Record<string, { label: string; color: string }> = { 
  az_tehlikeli: { label: 'Az Tehlikeli', color: 'emerald' }, 
  tehlikeli: { label: 'Tehlikeli', color: 'amber' }, 
  cok_tehlikeli: { label: 'Çok Tehlikeli', color: 'red' }
}

const hizmetLabels: Record<string, string> = {
  isyeri_hekimligi: 'İşyeri Hekimliği', is_guvenligi: 'İş Güvenliği Uzmanlığı',
  dsp: 'Diğer Sağlık Personeli', egitim: 'İSG Eğitimleri',
  risk_analizi: 'Risk Analizi', acil_durum: 'Acil Durum Planı',
}

export default function TekliflerPage() {
  const { user } = useAuth()
  const [quotes, setQuotes] = useState<QuoteRequest[]>([])
  const [serviceTypes, setServiceTypes] = useState<ServiceType[]>([])
  const [companies, setCompanies] = useState<Company[]>([])
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<'pending' | 'sent'>('pending')
  const [statusFilter, setStatusFilter] = useState('all')
  const [search, setSearch] = useState('')
  const [selectedQuote, setSelectedQuote] = useState<QuoteRequest | null>(null)
  const [detailStep, setDetailStep] = useState<1 | 2>(1)
  const [showManualModal, setShowManualModal] = useState(false)
  const [servicePrices, setServicePrices] = useState<ServicePrice[]>([])
  const [generatingPDF, setGeneratingPDF] = useState(false)
  const [sendingQuote, setSendingQuote] = useState(false)
  const [manualFormType, setManualFormType] = useState<'existing' | 'new'>('existing')
  const [manualForm, setManualForm] = useState({
    companyId: '',
    company_name: '', authorized_person: '', email: '',
    employee_count: '', tehlike_sinifi: 'tehlikeli',
    selectedServices: [] as string[]
  })
  const [manualServicePrices, setManualServicePrices] = useState<ServicePrice[]>([])
  
  const supabase = getSupabaseClient()

  const fetchQuotes = useCallback(async () => {
    if (!user) return
    setLoading(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const [quotesRes, servicesRes, companiesRes] = await Promise.all([
        (supabase as any).from('quote_requests').select('*').order('created_at', { ascending: false }),
        (supabase as any).from('service_types').select('id, name').order('name'),
        (supabase as any).from('companies').select('id, company_name, email, employee_count, tehlike_sinifi').eq('is_active', true).order('company_name')
      ])
      if (quotesRes.data) setQuotes(quotesRes.data)
      if (servicesRes.data) setServiceTypes(servicesRes.data)
      if (companiesRes.data) setCompanies(companiesRes.data)
    } catch (err) { console.error('Fetch error:', err) }
    setLoading(false)
  }, [user, supabase])

  useEffect(() => { if (user) fetchQuotes() }, [user, fetchQuotes])
  useVisibilityRefresh(fetchQuotes, !!user)

  const generateTeklifNo = () => {
    const year = new Date().getFullYear()
    const count = quotes.filter(q => q.created_at.startsWith(year.toString())).length + 1
    return `${year}-${count.toString().padStart(3, '0')}`
  }

  const openQuoteDetail = (quote: QuoteRequest) => {
    // Seçilen hizmetlerin fiyat listesini hazırla
    const prices: ServicePrice[] = []
    if (quote.requested_services && quote.requested_services.length > 0) {
      quote.requested_services.forEach(serviceId => {
        const service = serviceTypes.find(s => s.id === serviceId)
        if (service) {
          prices.push({ id: serviceId, name: service.name, price: '' })
        }
      })
    }
    // Eğer hizmet seçilmemişse varsayılan olarak İş Güvenliği ve İşyeri Hekimliği ekle
    if (prices.length === 0) {
      const isgUzman = serviceTypes.find(s => s.name.toLowerCase().includes('güvenliği'))
      const hekim = serviceTypes.find(s => s.name.toLowerCase().includes('hekim'))
      if (isgUzman) prices.push({ id: isgUzman.id, name: isgUzman.name, price: '' })
      if (hekim) prices.push({ id: hekim.id, name: hekim.name, price: '' })
    }
    setServicePrices(prices)
    setSelectedQuote(quote)
    setDetailStep(1)
  }

  const closeQuoteDetail = () => {
    setSelectedQuote(null)
    setDetailStep(1)
    setServicePrices([])
  }

  const openManualPDFModal = () => {
    setManualFormType('existing')
    setManualForm({ companyId: '', company_name: '', authorized_person: '', email: '', employee_count: '', tehlike_sinifi: 'tehlikeli', selectedServices: [] })
    setManualServicePrices([])
    setShowManualModal(true)
  }

  const handleCompanySelect = (companyId: string) => {
    const company = companies.find(c => c.id === companyId)
    if (company) {
      setManualForm(prev => ({
        ...prev,
        companyId,
        company_name: company.company_name,
        email: company.email,
        employee_count: company.employee_count?.toString() || '',
        tehlike_sinifi: company.tehlike_sinifi || 'tehlikeli'
      }))
    } else {
      setManualForm(prev => ({ ...prev, companyId: '' }))
    }
  }

  const toggleManualService = (serviceId: string) => {
    const service = serviceTypes.find(s => s.id === serviceId)
    if (!service) return
    
    setManualForm(prev => {
      const isSelected = prev.selectedServices.includes(serviceId)
      return {
        ...prev,
        selectedServices: isSelected 
          ? prev.selectedServices.filter(id => id !== serviceId)
          : [...prev.selectedServices, serviceId]
      }
    })
    
    setManualServicePrices(prev => {
      const exists = prev.find(p => p.id === serviceId)
      if (exists) {
        return prev.filter(p => p.id !== serviceId)
      } else {
        return [...prev, { id: serviceId, name: service.name, price: '' }]
      }
    })
  }

  const updateServicePrice = (id: string, price: string) => {
    setServicePrices(prev => prev.map(p => p.id === id ? { ...p, price } : p))
  }

  const updateManualServicePrice = (id: string, price: string) => {
    setManualServicePrices(prev => prev.map(p => p.id === id ? { ...p, price } : p))
  }

  const generateManualPDF = async () => {
    if (!manualForm.company_name || !manualForm.employee_count || manualServicePrices.length === 0) return
    // Tüm fiyatların girildiğini kontrol et
    if (manualServicePrices.some(p => !p.price)) {
      alert('Lütfen tüm hizmetlerin fiyatlarını girin')
      return
    }
    setGeneratingPDF(true)
    try {
      const services = manualServicePrices.map(p => ({
        name: p.name,
        price: parseFloat(p.price)
      }))
      
      const response = await fetch('/api/admin/teklif-pdf', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          teklifNo: generateTeklifNo(), 
          firmaAdi: manualForm.company_name,
          yetkili: manualForm.authorized_person || '-', 
          email: manualForm.email || '-',
          calisanSayisi: parseInt(manualForm.employee_count),
          tehlikeSinifi: manualForm.tehlike_sinifi,
          services
        }),
      })
      if (!response.ok) throw new Error('PDF oluşturulamadı')
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${generateTeklifNo()}_${manualForm.company_name.replace(/\s+/g, '_')}_Teklif.pdf`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
      setShowManualModal(false)
    } catch (err) { console.error('PDF error:', err); alert('PDF oluşturulurken hata oluştu') }
    setGeneratingPDF(false)
  }

  const generatePDF = async (sendToClient = false) => {
    if (!selectedQuote || servicePrices.length === 0) return
    // Tüm fiyatların girildiğini kontrol et
    if (servicePrices.some(p => !p.price)) {
      alert('Lütfen tüm hizmetlerin fiyatlarını girin')
      return
    }
    if (sendToClient) setSendingQuote(true)
    else setGeneratingPDF(true)
    
    try {
      const teklifNo = generateTeklifNo()
      const fileName = `${teklifNo}_${selectedQuote.company_name.replace(/\s+/g, '_')}_Teklif.pdf`
      
      const services = servicePrices.map(p => ({
        name: p.name,
        price: parseFloat(p.price)
      }))
      
      const response = await fetch('/api/admin/teklif-pdf', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          teklifNo, 
          firmaAdi: selectedQuote.company_name,
          yetkili: selectedQuote.authorized_person, 
          email: selectedQuote.email,
          calisanSayisi: selectedQuote.employee_count,
          tehlikeSinifi: selectedQuote.tehlike_sinifi || 'tehlikeli',
          services
        }),
      })
      if (!response.ok) throw new Error('PDF oluşturulamadı')
      const blob = await response.blob()
      
      // PDF'i indir
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
      
      // Eğer gönder seçildiyse status'u güncelle ve belgelere ekle
      if (sendToClient) {
        const totalPrice = services.reduce((sum, s) => sum + s.price, 0)
        const serviceDetails = services.map(s => `${s.name}: ${s.price.toLocaleString('tr-TR')} TL`).join(', ')
        const adminNote = `Teklif gönderildi - ${teklifNo} - ${serviceDetails} - Toplam: ${totalPrice.toLocaleString('tr-TR')} TL/ay`
        
        // Status güncelle
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { error: updateError } = await (supabase as any).from('quote_requests').update({ 
          status: 'quoted',
          notes: adminNote
        }).eq('id', selectedQuote.id)
        
        if (updateError) {
          console.error('Update error:', updateError)
        }
        
        // Portal'dan gelen teklif ise şirketin belgelerine ve storage'a ekle
        if (selectedQuote.source === 'portal') {
          // Şirket ID'sini email ile bul
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const { data: companyData } = await (supabase as any)
            .from('companies')
            .select('id')
            .eq('email', selectedQuote.email)
            .single()
          
          if (companyData) {
            // PDF'i Storage'a yükle
            const storagePath = `${companyData.id}/teklifler/${fileName}`
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const { error: uploadError } = await (supabase as any).storage
              .from('documents')
              .upload(storagePath, blob, {
                contentType: 'application/pdf',
                upsert: true
              })
            
            let fileUrl = null
            if (!uploadError) {
              // Public URL al
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              const { data: urlData } = (supabase as any).storage
                .from('documents')
                .getPublicUrl(storagePath)
              fileUrl = urlData?.publicUrl
            }
            
            // Belgelere teklif PDF'ini ekle
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            await (supabase as any).from('documents').insert({
              company_id: companyData.id,
              title: `Teklif - ${teklifNo}`,
              description: `${selectedQuote.employee_count} çalışan için ISG hizmet teklifi. Toplam: ${totalPrice.toLocaleString('tr-TR')} TL/ay`,
              document_type: 'diger',
              status: 'draft',
              file_url: fileUrl,
              file_name: fileName,
              mime_type: 'application/pdf'
            })
          }
        }
        
        setQuotes(prev => prev.map(q => q.id === selectedQuote.id ? { ...q, status: 'quoted', notes: adminNote } : q))
        setSelectedQuote({ ...selectedQuote, status: 'quoted', notes: adminNote })
      }
      
      closeQuoteDetail()
    } catch (err) { console.error('PDF error:', err); alert('PDF oluşturulurken hata oluştu') }
    setGeneratingPDF(false)
    setSendingQuote(false)
  }
  // Filtreleme - Tab'a göre status grupları
  const pendingQuotes = quotes.filter(q => pendingStatuses.includes(q.status))
  const sentQuotes = quotes.filter(q => sentStatuses.includes(q.status))
  
  const filtered = quotes.filter(q => {
    const matchesTab = activeTab === 'pending' 
      ? pendingStatuses.includes(q.status) 
      : sentStatuses.includes(q.status)
    const matchesStatus = statusFilter === 'all' || q.status === statusFilter
    const matchesSearch = q.company_name.toLowerCase().includes(search.toLowerCase()) ||
                          q.authorized_person.toLowerCase().includes(search.toLowerCase())
    return matchesTab && matchesStatus && matchesSearch
  })

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('tr-TR', {
      day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit'
    })
  }

  return (
    <div className="space-y-6">
      {/* Header with Tabs */}
      <div className="flex flex-col gap-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <h1 className="page-title">Teklif Talepleri</h1>
          
          <div className="flex items-center gap-2 sm:gap-3">
            <button onClick={openManualPDFModal}
              className="flex items-center gap-1.5 sm:gap-2 px-3 sm:px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-xl text-sm font-medium transition-colors">
              <Plus className="w-4 h-4" /> <span className="hidden sm:inline">Yeni Teklif</span><span className="sm:hidden">Yeni</span>
            </button>
            <button onClick={fetchQuotes} disabled={loading}
              className="flex items-center gap-2 px-3 sm:px-4 py-2 bg-white border border-gray-200 hover:bg-gray-50 text-gray-600 rounded-xl transition-colors disabled:opacity-50">
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} /> <span className="hidden sm:inline">Yenile</span>
            </button>
          </div>
        </div>
        
        {/* Tabs */}
        <div className="flex items-center bg-gray-100 rounded-lg p-1 w-fit">
          <button onClick={() => setActiveTab('pending')}
            className={`px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all flex items-center gap-1.5 sm:gap-2 ${
              activeTab === 'pending' ? 'bg-white text-amber-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}>
            <Clock className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> Bekleyen ({pendingQuotes.length})
          </button>
          <button onClick={() => setActiveTab('sent')}
            className={`px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all flex items-center gap-1.5 sm:gap-2 ${
              activeTab === 'sent' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}>
            <Send className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> Gönderilen ({sentQuotes.length})
          </button>
        </div>
      </div>

      {/* Search & Filter */}
      <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input type="text" placeholder="Şirket veya yetkili ara..." value={search} onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400" />
        </div>
        <div className="min-w-[140px]">
          <CustomSelect
            name="statusFilter"
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            placeholder="Tümü"
            variant="admin"
            options={activeTab === 'pending' 
              ? [{ value: 'all', label: 'Tümü' }, { value: 'pending', label: 'Bekliyor' }]
              : [
                  { value: 'all', label: 'Tümü' },
                  { value: 'quoted', label: 'Teklif Gönderildi' },
                  { value: 'reviewing', label: 'Şirket İnceliyor' },
                  { value: 'accepted', label: 'Şirket Onayladı' },
                  { value: 'rejected', label: 'Şirket Reddetti' },
                  { value: 'expired', label: 'Süresi Doldu' },
                ]
            }
          />
        </div>
      </div>

      {/* List - Cards on mobile, Table on desktop */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {loading && quotes.length === 0 ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-center py-12">
            <FileText className="w-10 h-10 text-gray-200 mx-auto mb-2" />
            <p className="text-gray-400 text-sm">Teklif talebi bulunamadı</p>
          </div>
        ) : (
          <>
            {/* Mobile Card View */}
            <div className="md:hidden divide-y divide-gray-100">
              {filtered.map((quote) => {
                const status = statusConfig[quote.status as keyof typeof statusConfig] || statusConfig.pending
                const tehlike = quote.tehlike_sinifi ? tehlikeConfig[quote.tehlike_sinifi] : null
                return (
                  <div key={quote.id} onClick={() => openQuoteDetail(quote)} 
                    className="p-4 hover:bg-gray-50 transition-colors cursor-pointer active:bg-gray-100">
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex items-start gap-3 min-w-0 flex-1">
                        <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                          <Building2 className="w-5 h-5 text-gray-400" />
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-semibold text-gray-800 truncate">{quote.company_name}</p>
                          <p className="text-xs text-gray-500 truncate">{quote.authorized_person}</p>
                          <div className="flex flex-wrap items-center gap-1.5 mt-2">
                            <span className={`inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-medium rounded-md ${
                              quote.source === 'portal' ? 'bg-purple-50 text-purple-600' : 'bg-gray-100 text-gray-600'
                            }`}>
                              {quote.source === 'portal' ? 'Portal' : 'Web'}
                            </span>
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-medium rounded-md bg-gray-100 text-gray-600">
                              <Users className="w-3 h-3" /> {quote.employee_count}
                            </span>
                            {tehlike && (
                              <span className={`px-2 py-0.5 text-[10px] font-medium rounded-md ${
                                tehlike.color === 'emerald' ? 'bg-emerald-50 text-emerald-600' :
                                tehlike.color === 'amber' ? 'bg-amber-50 text-amber-600' : 'bg-red-50 text-red-600'
                              }`}>
                                {tehlike.label}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex flex-col items-end gap-2 flex-shrink-0">
                        <span className={`px-2 py-1 text-[10px] font-medium rounded-md whitespace-nowrap ${
                          status.color === 'amber' ? 'bg-amber-50 text-amber-600' :
                          status.color === 'blue' ? 'bg-blue-50 text-blue-600' :
                          status.color === 'purple' ? 'bg-purple-50 text-purple-600' :
                          status.color === 'green' ? 'bg-emerald-50 text-emerald-600' : 'bg-red-50 text-red-600'
                        }`}>{status.label}</span>
                        <ChevronRight className="w-4 h-4 text-gray-300" />
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>

            {/* Desktop Table View */}
            <table className="w-full hidden md:table">
              <thead className="bg-gray-50 border-b border-gray-100">
                <tr>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Şirket</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Kaynak</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Çalışan</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider hidden lg:table-cell">Tehlike</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Durum</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider hidden lg:table-cell">Tarih</th>
                  <th className="px-4 py-3 text-right text-[11px] font-semibold text-gray-400 uppercase tracking-wider">İşlem</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {filtered.map((quote) => {
                  const status = statusConfig[quote.status as keyof typeof statusConfig] || statusConfig.pending
                  const tehlike = quote.tehlike_sinifi ? tehlikeConfig[quote.tehlike_sinifi] : null
                  return (
                    <tr key={quote.id} className="hover:bg-gray-50/50 transition-colors group">
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-3">
                          <div className="w-9 h-9 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                            <Building2 className="w-4 h-4 text-gray-400" />
                          </div>
                          <div className="min-w-0">
                            <p className="text-sm font-medium text-gray-800 truncate">{quote.company_name}</p>
                            <p className="text-xs text-gray-400 truncate">{quote.authorized_person}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-4">
                        <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-lg ${
                          quote.source === 'portal' ? 'bg-purple-50 text-purple-600' : 'bg-gray-100 text-gray-600'
                        }`}>
                          {quote.source === 'portal' ? <Briefcase className="w-3 h-3" /> : <Globe className="w-3 h-3" />}
                          <span className="hidden lg:inline">{quote.source === 'portal' ? 'Şirket Portalı' : 'Web Sitesi'}</span>
                          <span className="lg:hidden">{quote.source === 'portal' ? 'Portal' : 'Web'}</span>
                        </span>
                      </td>
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-1.5 text-sm text-gray-600">
                          <Users className="w-4 h-4 text-gray-400" /> {quote.employee_count}
                        </div>
                      </td>
                      <td className="px-4 py-4 hidden lg:table-cell">
                        {tehlike ? (
                          <span className={`px-2.5 py-1 text-xs font-medium rounded-lg ${
                            tehlike.color === 'emerald' ? 'bg-emerald-50 text-emerald-600' :
                            tehlike.color === 'amber' ? 'bg-amber-50 text-amber-600' : 'bg-red-50 text-red-600'
                          }`}>
                            {tehlike.label}
                          </span>
                        ) : <span className="text-gray-300 text-xs">-</span>}
                      </td>
                      <td className="px-4 py-4">
                        <span className={`px-2.5 py-1 text-xs font-medium rounded-lg ${
                          status.color === 'amber' ? 'bg-amber-50 text-amber-600' :
                          status.color === 'blue' ? 'bg-blue-50 text-blue-600' :
                          status.color === 'purple' ? 'bg-purple-50 text-purple-600' :
                          status.color === 'green' ? 'bg-emerald-50 text-emerald-600' : 'bg-red-50 text-red-600'
                        }`}>{status.label}</span>
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-400 hidden lg:table-cell">{formatDate(quote.created_at)}</td>
                      <td className="px-4 py-4">
                        <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                          <button onClick={() => openQuoteDetail(quote)} title="Detaylar"
                            className="p-2 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-lg transition-colors">
                            <ChevronRight className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </>
        )}
      </div>

      {/* Quote Detail Modal - 2 Adımlı */}
      {selectedQuote && (
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
          className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-2 sm:p-4" onClick={closeQuoteDetail}>
          <motion.div initial={{ scale: 0.95 }} animate={{ scale: 1 }} onClick={(e) => e.stopPropagation()}
            className="bg-white rounded-2xl w-full max-w-2xl max-h-[95vh] sm:max-h-[90vh] overflow-hidden border border-gray-200 shadow-xl flex flex-col">
            
            {/* Header */}
            <div className="p-5 border-b border-gray-100 flex items-start justify-between flex-shrink-0">
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <h2 className="text-lg font-semibold text-gray-800">{selectedQuote.company_name}</h2>
                  <span className={`px-2 py-0.5 text-xs font-medium rounded-md ${
                    selectedQuote.source === 'portal' ? 'bg-purple-50 text-purple-600' : 'bg-gray-100 text-gray-500'
                  }`}>{selectedQuote.source === 'portal' ? 'Portal' : 'Web'}</span>
                </div>
                <p className="text-gray-400 text-sm">{selectedQuote.authorized_person}</p>
              </div>
              <div className="flex items-center gap-2">
                <div className="flex items-center gap-1 mr-2">
                  <span className={`w-2 h-2 rounded-full ${detailStep === 1 ? 'bg-blue-500' : 'bg-gray-300'}`} />
                  <span className={`w-2 h-2 rounded-full ${detailStep === 2 ? 'bg-blue-500' : 'bg-gray-300'}`} />
                </div>
                <span className={`px-3 py-1 text-xs font-medium rounded-lg ${
                  selectedQuote.status === 'pending' ? 'bg-amber-50 text-amber-600' :
                  selectedQuote.status === 'reviewing' ? 'bg-purple-50 text-purple-600' :
                  selectedQuote.status === 'quoted' ? 'bg-blue-50 text-blue-600' :
                  selectedQuote.status === 'accepted' ? 'bg-emerald-50 text-emerald-600' : 'bg-red-50 text-red-600'
                }`}>{statusConfig[selectedQuote.status as keyof typeof statusConfig]?.label || 'Bekliyor'}</span>
              </div>
            </div>
            
            {/* Content */}
            <div className="p-5 space-y-5 overflow-y-auto flex-1">
              {detailStep === 1 ? (
                <>
                  <div>
                    <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">İletişim</h3>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div className="bg-gray-50 rounded-xl p-3">
                        <p className="text-[10px] text-gray-400 mb-1">E-posta</p>
                        <a href={`mailto:${selectedQuote.email}`} className="text-sm text-blue-500 hover:underline break-all">{selectedQuote.email}</a>
                      </div>
                      <div className="bg-gray-50 rounded-xl p-3">
                        <p className="text-[10px] text-gray-400 mb-1">Telefon</p>
                        <a href={`tel:${selectedQuote.phone}`} className="text-sm text-blue-500 hover:underline">{selectedQuote.phone}</a>
                      </div>
                    </div>
                  </div>
                  <div>
                    <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">İSG Bilgileri</h3>
                    <div className="grid grid-cols-3 gap-2 sm:gap-3">
                      <div className="bg-gray-50 rounded-xl p-2 sm:p-3">
                        <p className="text-[10px] text-gray-400 mb-1">Çalışan</p>
                        <p className="text-base sm:text-lg font-semibold text-gray-800">{selectedQuote.employee_count}</p>
                      </div>
                      <div className="bg-gray-50 rounded-xl p-2 sm:p-3">
                        <p className="text-[10px] text-gray-400 mb-1">Tehlike</p>
                        <p className={`text-base sm:text-lg font-semibold ${
                          selectedQuote.tehlike_sinifi === 'az_tehlikeli' ? 'text-emerald-600' :
                          selectedQuote.tehlike_sinifi === 'tehlikeli' ? 'text-amber-600' : 'text-red-600'
                        }`}>{selectedQuote.tehlike_sinifi ? tehlikeConfig[selectedQuote.tehlike_sinifi]?.label : '-'}</p>
                      </div>
                      <div className="bg-gray-50 rounded-xl p-2 sm:p-3">
                        <p className="text-[10px] text-gray-400 mb-1">Şehir</p>
                        <p className="text-base sm:text-lg font-semibold text-gray-800 truncate">{selectedQuote.city || '-'}</p>
                      </div>
                    </div>
                  </div>
                  {(selectedQuote.hekim_suresi || selectedQuote.uzman_suresi || selectedQuote.dsp_suresi) && (
                    <div>
                      <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">Süreler (dk/ay)</h3>
                      <div className="grid grid-cols-3 gap-2 sm:gap-3">
                        {selectedQuote.uzman_suresi && <div className="bg-emerald-50 rounded-xl p-2 sm:p-3 text-center"><p className="text-[10px] text-emerald-600 mb-1">Uzman</p><p className="text-base sm:text-lg font-semibold">{selectedQuote.uzman_suresi}</p></div>}
                        {selectedQuote.hekim_suresi && <div className="bg-blue-50 rounded-xl p-2 sm:p-3 text-center"><p className="text-[10px] text-blue-600 mb-1">Hekim</p><p className="text-base sm:text-lg font-semibold">{selectedQuote.hekim_suresi}</p></div>}
                        {selectedQuote.dsp_suresi && <div className="bg-purple-50 rounded-xl p-2 sm:p-3 text-center"><p className="text-[10px] text-purple-600 mb-1">DSP</p><p className="text-base sm:text-lg font-semibold">{selectedQuote.dsp_suresi}</p></div>}
                      </div>
                    </div>
                  )}
                  {selectedQuote.requested_services && selectedQuote.requested_services.length > 0 && (
                    <div>
                      <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">Talep Edilen Hizmetler</h3>
                      <div className="flex flex-wrap gap-2">
                        {selectedQuote.requested_services.map((s: string) => {
                          const service = serviceTypes.find(st => st.id === s)
                          return (
                            <span key={s} className="px-3 py-1.5 bg-blue-50 text-blue-600 rounded-lg text-xs font-medium">
                              {service?.name || hizmetLabels[s] || s}
                            </span>
                          )
                        })}
                      </div>
                    </div>
                  )}
                  {selectedQuote.notes && (
                    <div>
                      <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">Notlar</h3>
                      <div className="bg-gray-50 rounded-xl p-4"><p className="text-sm text-gray-600 whitespace-pre-wrap">{selectedQuote.notes}</p></div>
                    </div>
                  )}
                  {(selectedQuote.status === 'accepted' || selectedQuote.status === 'rejected' || selectedQuote.status === 'reviewing') && (
                    <div className={`p-3 rounded-xl text-sm ${
                      selectedQuote.status === 'accepted' ? 'bg-emerald-50 text-emerald-700' :
                      selectedQuote.status === 'rejected' ? 'bg-red-50 text-red-700' :
                      'bg-purple-50 text-purple-700'
                    }`}>
                      {selectedQuote.status === 'accepted' && '✓ Şirket bu teklifi onayladı'}
                      {selectedQuote.status === 'rejected' && '✗ Şirket bu teklifi reddetti'}
                      {selectedQuote.status === 'reviewing' && '⏳ Şirket teklifi inceliyor'}
                    </div>
                  )}
                  <p className="text-xs text-gray-300">{formatDate(selectedQuote.created_at)}</p>
                </>
              ) : (
                <>
                  <div className="grid grid-cols-2 gap-2 sm:gap-3">
                    <div className="bg-gray-50 rounded-xl p-2 sm:p-3">
                      <p className="text-xs text-gray-400 mb-1">Çalışan</p>
                      <p className="text-base sm:text-lg font-semibold text-gray-800">{selectedQuote.employee_count}</p>
                    </div>
                    <div className="bg-gray-50 rounded-xl p-2 sm:p-3">
                      <p className="text-xs text-gray-400 mb-1">Tehlike Sınıfı</p>
                      <p className={`text-base sm:text-lg font-semibold ${
                        selectedQuote.tehlike_sinifi === 'az_tehlikeli' ? 'text-emerald-600' :
                        selectedQuote.tehlike_sinifi === 'tehlikeli' ? 'text-amber-600' : 'text-red-600'
                      }`}>
                        {selectedQuote.tehlike_sinifi ? tehlikeConfig[selectedQuote.tehlike_sinifi]?.label : '-'}
                      </p>
                    </div>
                  </div>
              
                  <div>
                    <label className="block text-sm font-medium text-gray-600 mb-2">Hizmet Fiyatları (Aylık TL)</label>
                    <div className="space-y-2">
                      {servicePrices.map((service) => (
                        <div key={service.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                          <span className="flex-1 text-sm text-gray-700">{service.name}</span>
                          <input 
                            type="number" 
                            value={service.price} 
                            onChange={(e) => updateServicePrice(service.id, e.target.value)} 
                            placeholder="0"
                            className="w-32 px-3 py-2 bg-white border border-gray-200 rounded-lg text-gray-800 text-right focus:outline-none focus:ring-2 focus:ring-blue-500/20" 
                          />
                          <span className="text-gray-400 text-sm">₺</span>
                        </div>
                      ))}
                    </div>
                  </div>
                  {servicePrices.some(p => p.price) && (
                    <div className="bg-emerald-50 border border-emerald-100 rounded-xl p-4 flex justify-between items-center">
                      <span className="text-gray-600 text-sm">Toplam Aylık:</span>
                      <span className="text-xl font-bold text-emerald-600">
                        {servicePrices.reduce((sum, p) => sum + (parseFloat(p.price) || 0), 0).toLocaleString('tr-TR')} TL
                      </span>
                    </div>
                  )}
                </>
              )}
            </div>
            
            {/* Footer */}
            <div className="p-3 sm:p-5 border-t border-gray-100 flex flex-col sm:flex-row gap-2 sm:gap-3 flex-shrink-0">
              {detailStep === 1 ? (
                <>
                  <button onClick={closeQuoteDetail} className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-medium transition-colors text-sm sm:text-base">Kapat</button>
                  {(selectedQuote.status === 'pending' || selectedQuote.status === 'quoted') && (
                    <button onClick={() => setDetailStep(2)} className="flex-1 px-4 py-2.5 bg-blue-500 hover:bg-blue-600 text-white rounded-xl font-medium transition-colors flex items-center justify-center gap-2 text-sm sm:text-base">
                      <FileText className="w-4 h-4" /> Teklif Hazırla
                    </button>
                  )}
                </>
              ) : (
                <>
                  <button onClick={() => setDetailStep(1)} className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-medium transition-colors text-sm sm:text-base">Geri</button>
                  <button onClick={() => generatePDF(false)} disabled={servicePrices.some(p => !p.price) || generatingPDF || sendingQuote}
                    className="flex-1 px-3 sm:px-4 py-2.5 bg-gray-600 hover:bg-gray-700 text-white rounded-xl font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-1.5 sm:gap-2 text-xs sm:text-sm">
                    {generatingPDF ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
                    {generatingPDF ? 'İndiriliyor...' : <><span className="hidden sm:inline">Sadece</span> İndir</>}
                  </button>
                  <button onClick={() => generatePDF(true)} disabled={servicePrices.some(p => !p.price) || generatingPDF || sendingQuote}
                    className="flex-1 px-3 sm:px-4 py-2.5 bg-emerald-500 hover:bg-emerald-600 text-white rounded-xl font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-1.5 sm:gap-2 text-xs sm:text-sm">
                    {sendingQuote ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
                    {sendingQuote ? 'Gönderiliyor...' : <><span className="hidden sm:inline">İndir ve</span> Gönder</>}
                  </button>
                </>
              )}
            </div>
          </motion.div>
        </motion.div>
      )}

      {/* Manual Quote Modal */}
      {showManualModal && (
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
          className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-2 sm:p-4" onClick={() => setShowManualModal(false)}>
          <motion.div initial={{ scale: 0.95 }} animate={{ scale: 1 }} onClick={(e) => e.stopPropagation()}
            className="bg-white rounded-2xl w-full max-w-lg border border-gray-200 shadow-xl max-h-[95vh] sm:max-h-[85vh] flex flex-col">
            <div className="p-5 border-b border-gray-100 flex items-center justify-between flex-shrink-0">
              <div>
                <h2 className="text-lg font-semibold text-gray-800">Yeni Teklif Oluştur</h2>
                <p className="text-gray-400 text-sm">Manuel teklif PDF&apos;i oluşturun</p>
              </div>
              <button onClick={() => setShowManualModal(false)} className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-5 space-y-4 overflow-y-auto flex-1">
              {/* Şirket Tipi Seçimi */}
              <div className="flex items-center bg-gray-100 rounded-lg p-1">
                <button onClick={() => { setManualFormType('existing'); setManualForm(prev => ({ ...prev, companyId: '', company_name: '', email: '', employee_count: '', tehlike_sinifi: 'tehlikeli' })) }}
                  className={`flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all ${
                    manualFormType === 'existing' ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500 hover:text-gray-700'
                  }`}>
                  Mevcut Şirket
                </button>
                <button onClick={() => { setManualFormType('new'); setManualForm(prev => ({ ...prev, companyId: '' })) }}
                  className={`flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all ${
                    manualFormType === 'new' ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500 hover:text-gray-700'
                  }`}>
                  Yeni Şirket
                </button>
              </div>

              {manualFormType === 'existing' ? (
                /* Mevcut Şirket Seçimi */
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-1.5">Şirket Seç *</label>
                  <CustomSelect
                    name="companyId"
                    value={manualForm.companyId}
                    onChange={(e) => handleCompanySelect(e.target.value)}
                    placeholder="Şirket seçin..."
                    variant="admin"
                    options={companies.map(c => ({ value: c.id, label: `${c.company_name} (${c.employee_count || 0} çalışan)` }))}
                  />
                  {manualForm.companyId && (
                    <div className="mt-3 p-3 bg-gray-50 rounded-xl grid grid-cols-2 gap-2 text-sm">
                      <div><span className="text-gray-400">E-posta:</span> <span className="text-gray-700">{manualForm.email}</span></div>
                      <div><span className="text-gray-400">Çalışan:</span> <span className="text-gray-700">{manualForm.employee_count}</span></div>
                      <div className="col-span-2"><span className="text-gray-400">Tehlike:</span> <span className={`font-medium ${
                        manualForm.tehlike_sinifi === 'az_tehlikeli' ? 'text-emerald-600' :
                        manualForm.tehlike_sinifi === 'tehlikeli' ? 'text-amber-600' : 'text-red-600'
                      }`}>{tehlikeConfig[manualForm.tehlike_sinifi]?.label || '-'}</span></div>
                    </div>
                  )}
                </div>
              ) : (
                /* Yeni Şirket Bilgileri */
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-600 mb-1.5">Firma Adı *</label>
                    <input type="text" value={manualForm.company_name} onChange={(e) => setManualForm({...manualForm, company_name: e.target.value})}
                      placeholder="Örn: ABC Şirketi" className="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-600 mb-1.5">Yetkili Kişi</label>
                      <input type="text" value={manualForm.authorized_person} onChange={(e) => setManualForm({...manualForm, authorized_person: e.target.value})}
                        placeholder="Ad Soyad" className="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-600 mb-1.5">E-posta</label>
                      <input type="email" value={manualForm.email} onChange={(e) => setManualForm({...manualForm, email: e.target.value})}
                        placeholder="ornek@firma.com" className="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-600 mb-1.5">Çalışan Sayısı *</label>
                      <input type="number" value={manualForm.employee_count} onChange={(e) => setManualForm({...manualForm, employee_count: e.target.value})}
                        placeholder="50" className="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-600 mb-1.5">Tehlike Sınıfı *</label>
                      <CustomSelect
                        name="tehlike_sinifi"
                        value={manualForm.tehlike_sinifi}
                        onChange={(e) => setManualForm({...manualForm, tehlike_sinifi: e.target.value})}
                        placeholder="Seçiniz"
                        variant="admin"
                        icon={<AlertTriangle className="w-5 h-5 text-gray-400" />}
                        options={[
                          { value: 'az_tehlikeli', label: 'Az Tehlikeli' },
                          { value: 'tehlikeli', label: 'Tehlikeli' },
                          { value: 'cok_tehlikeli', label: 'Çok Tehlikeli' },
                        ]}
                      />
                    </div>
                  </div>
                </>
              )}
              
              {/* Hizmet Seçimi */}
              <div>
                <label className="block text-sm font-medium text-gray-600 mb-2">Hizmetler *</label>
                <div className="grid grid-cols-2 gap-2 max-h-32 overflow-y-auto">
                  {serviceTypes.map(service => (
                    <label key={service.id}
                      className={`flex items-center gap-2 p-2 rounded-lg border cursor-pointer transition-all text-xs ${
                        manualForm.selectedServices.includes(service.id)
                          ? 'bg-blue-50 border-blue-200 text-blue-700'
                          : 'bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100'
                      }`}>
                      <input type="checkbox" checked={manualForm.selectedServices.includes(service.id)}
                        onChange={() => toggleManualService(service.id)} className="sr-only" />
                      <span className="truncate">{service.name}</span>
                    </label>
                  ))}
                </div>
              </div>
              
              {/* Seçilen Hizmetlerin Fiyatları */}
              {manualServicePrices.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-2">Hizmet Fiyatları (Aylık TL)</label>
                  <div className="space-y-2">
                    {manualServicePrices.map((service) => (
                      <div key={service.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                        <span className="flex-1 text-sm text-gray-700">{service.name}</span>
                        <input 
                          type="number" 
                          value={service.price} 
                          onChange={(e) => updateManualServicePrice(service.id, e.target.value)} 
                          placeholder="0"
                          className="w-32 px-3 py-2 bg-white border border-gray-200 rounded-lg text-gray-800 text-right focus:outline-none focus:ring-2 focus:ring-blue-500/20" 
                        />
                        <span className="text-gray-400 text-sm">₺</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              
              {/* Toplam */}
              {manualServicePrices.some(p => p.price) && (
                <div className="bg-emerald-50 border border-emerald-100 rounded-xl p-4 flex justify-between items-center">
                  <span className="text-gray-600 text-sm">Toplam Aylık:</span>
                  <span className="text-xl font-bold text-emerald-600">
                    {manualServicePrices.reduce((sum, p) => sum + (parseFloat(p.price) || 0), 0).toLocaleString('tr-TR')} TL
                  </span>
                </div>
              )}
            </div>
            <div className="p-5 border-t border-gray-100 flex gap-3 flex-shrink-0">
              <button onClick={() => setShowManualModal(false)} className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-medium transition-colors">İptal</button>
              <button onClick={generateManualPDF} disabled={
                (manualFormType === 'existing' ? !manualForm.companyId : (!manualForm.company_name || !manualForm.employee_count)) || 
                manualServicePrices.length === 0 || 
                manualServicePrices.some(p => !p.price) || 
                generatingPDF
              }
                className="flex-1 px-4 py-2.5 bg-blue-500 hover:bg-blue-600 text-white rounded-xl font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-2">
                {generatingPDF ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
                {generatingPDF ? 'Oluşturuluyor...' : 'PDF Oluştur'}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </div>
  )
}
