"use client"

import { useState, useEffect, useCallback } from 'react'
import { 
  Send, CheckCircle, AlertCircle, Loader2, Plus, X, Clock, Eye, FileText, RefreshCw, XCircle
} from 'lucide-react'
import { useAuth } from '@/lib/auth/AuthProvider'
import { getSupabaseClient } from '@/lib/supabase/client'

const tehlikeSiniflari = [
  { value: 'az_tehlikeli', label: 'Az Tehlikeli', color: 'emerald' },
  { value: 'tehlikeli', label: 'Tehlikeli', color: 'amber' },
  { value: 'cok_tehlikeli', label: 'Çok Tehlikeli', color: 'red' },
]

const statusConfig: Record<string, { label: string; bg: string; text: string }> = {
  pending: { label: 'Beklemede', bg: 'bg-amber-100', text: 'text-amber-700' },
  quoted: { label: 'Teklif Geldi', bg: 'bg-blue-100', text: 'text-blue-700' },
  reviewing: { label: 'İnceliyorsunuz', bg: 'bg-purple-100', text: 'text-purple-700' },
  accepted: { label: 'Onayladınız', bg: 'bg-emerald-100', text: 'text-emerald-700' },
  rejected: { label: 'Reddettiniz', bg: 'bg-red-100', text: 'text-red-700' },
  expired: { label: 'Süresi Doldu', bg: 'bg-gray-100', text: 'text-gray-700' },
}

interface ServiceType { id: string; name: string }

interface QuoteRequest {
  id: string
  company_name: string
  email: string
  employee_count: number
  tehlike_sinifi: string | null
  requested_services: string[] | null
  notes: string | null
  status: string
  created_at: string
}

interface QuoteDocument {
  id: string
  title: string
  file_url: string | null
}

export default function TekliflerimPage() {
  const { user, profile } = useAuth()
  const [quotes, setQuotes] = useState<QuoteRequest[]>([])
  const [serviceTypes, setServiceTypes] = useState<ServiceType[]>([])
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<'requests' | 'received'>('requests')
  const [showNewForm, setShowNewForm] = useState(false)
  const [formData, setFormData] = useState({
    companyName: '', employeeCount: '', tehlikeSinifi: '',
    selectedServices: [] as string[], notes: ''
  })
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const supabase = getSupabaseClient()

  const fetchData = useCallback(async () => {
    if (!user) return
    setLoading(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data: company } = await (supabase as any)
        .from('companies').select('id, company_name, employee_count, tehlike_sinifi, email')
        .eq('profile_id', user.id).single()

      if (company) {
        setFormData(prev => ({
          ...prev, companyName: company.company_name || '',
          employeeCount: company.employee_count?.toString() || '',
          tehlikeSinifi: company.tehlike_sinifi || ''
        }))
        
        // Email veya şirket adı ile eşleşen teklifleri getir
        const userEmail = profile?.email || user.email || ''
        const companyEmail = company.email || ''
        const companyName = company.company_name || ''
        
        // Tüm teklifleri çek ve client-side filtrele (daha güvenilir)
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { data: allQuotes } = await (supabase as any)
          .from('quote_requests').select('*')
          .order('created_at', { ascending: false })
        
        if (allQuotes) {
          // Email veya şirket adı eşleşmesi
          const filteredQuotes = allQuotes.filter((q: QuoteRequest) => 
            q.email === companyEmail || 
            q.email === userEmail || 
            q.company_name.toLowerCase() === companyName.toLowerCase()
          )
          setQuotes(filteredQuotes)
        }
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data: services } = await (supabase as any)
        .from('service_types').select('id, name').order('name')
      if (services) setServiceTypes(services)
    } catch (err) { console.error('Fetch error:', err) }
    setLoading(false)
  }, [user, profile, supabase])

  useEffect(() => { if (user) fetchData() }, [user, fetchData])

  const toggleService = (id: string) => {
    setFormData(prev => ({
      ...prev,
      selectedServices: prev.selectedServices.includes(id)
        ? prev.selectedServices.filter(s => s !== id)
        : [...prev.selectedServices, id]
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true); setError(''); setSuccess('')
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { error: insertError } = await (supabase as any).from('quote_requests').insert({
        company_name: formData.companyName,
        authorized_person: profile?.full_name || 'Portal Kullanıcısı',
        email: profile?.email || user?.email || '',
        phone: profile?.phone || '',
        employee_count: parseInt(formData.employeeCount) || 0,
        tehlike_sinifi: formData.tehlikeSinifi || null,
        requested_services: formData.selectedServices,
        notes: formData.notes || null,
        source: 'portal', status: 'pending'
      })
      if (insertError) throw insertError
      setSuccess('Teklif talebiniz gönderildi!')
      setFormData(prev => ({ ...prev, selectedServices: [], notes: '' }))
      setShowNewForm(false); fetchData()
      setTimeout(() => setSuccess(''), 3000)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Gönderilemedi')
    }
    setIsSubmitting(false)
  }

  const formatDate = (d: string) => new Date(d).toLocaleDateString('tr-TR', { day: '2-digit', month: '2-digit', year: 'numeric' })
  const getServiceNames = (ids: string[] | null) => {
    if (!ids || ids.length === 0) return '-'
    return ids.map(id => serviceTypes.find(s => s.id === id)?.name || id).join(', ')
  }

  const updateQuoteStatus = async (quoteId: string, newStatus: string) => {
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { error } = await (supabase as any)
        .from('quote_requests')
        .update({ status: newStatus })
        .eq('id', quoteId)
      
      if (error) throw error
      
      // Eğer onaylandıysa, hizmetleri şirkete ekle
      if (newStatus === 'accepted') {
        const quote = quotes.find(q => q.id === quoteId)
        if (quote?.requested_services && quote.requested_services.length > 0) {
          // Şirket ID'sini bul
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const { data: company } = await (supabase as any)
            .from('companies')
            .select('id, employee_count')
            .eq('profile_id', user?.id)
            .single()
          
          if (company) {
            // Teklif notlarından fiyatı çıkar (varsa)
            let pricePerPerson = 0
            if (quote.notes) {
              const priceMatch = quote.notes.match(/Kişi başı:\s*(\d+)/i)
              if (priceMatch) pricePerPerson = parseInt(priceMatch[1])
            }
            
            // Her hizmet için company_services'a ekle
            const servicesToInsert = quote.requested_services.map(serviceId => ({
              company_id: company.id,
              service_type_id: serviceId,
              status: 'active',
              start_date: new Date().toISOString().split('T')[0],
              price: pricePerPerson > 0 ? pricePerPerson * (company.employee_count || 1) : null
            }))
            
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            await (supabase as any).from('company_services').insert(servicesToInsert)
          }
        }
      }
      
      // Local state güncelle
      setQuotes(prev => prev.map(q => q.id === quoteId ? { ...q, status: newStatus } : q))
    } catch (err) {
      console.error('Status update error:', err)
    }
  }

  // PDF'i aç ve status'u reviewing yap
  const openQuotePDF = async (quote: QuoteRequest) => {
    try {
      // Şirketin company_id'sini bul
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data: company } = await (supabase as any)
        .from('companies')
        .select('id')
        .eq('profile_id', user?.id)
        .single()
      
      if (company) {
        // Bu teklif için belgeyi bul
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { data: doc } = await (supabase as any)
          .from('documents')
          .select('id, title, file_url')
          .eq('company_id', company.id)
          .ilike('title', `%Teklif%`)
          .order('created_at', { ascending: false })
          .limit(1)
          .single()
        
        if (doc?.file_url) {
          // PDF'i yeni sekmede aç
          window.open(doc.file_url, '_blank')
        } else {
          alert('Teklif PDF\'i henüz yüklenmemiş')
        }
      }
      
      // Status'u reviewing yap
      await updateQuoteStatus(quote.id, 'reviewing')
    } catch (err) {
      console.error('PDF open error:', err)
      // Yine de status'u güncelle
      await updateQuoteStatus(quote.id, 'reviewing')
    }
  }

  // Filtreleme
  const pendingQuotes = quotes.filter(q => q.status === 'pending')
  const receivedQuotes = quotes.filter(q => q.status !== 'pending')
  const displayedQuotes = activeTab === 'requests' ? pendingQuotes : receivedQuotes

  if (loading) return <div className="flex items-center justify-center py-20"><Loader2 className="w-8 h-8 text-blue-500 animate-spin" /></div>

  return (
    <div className="space-y-4 sm:space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:gap-4">
        <div className="flex items-center justify-between">
          <h1 className="text-lg sm:text-xl font-semibold text-gray-800">Tekliflerim</h1>
          <div className="flex items-center gap-2">
            <button onClick={() => setShowNewForm(true)} 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 Talep</span><span className="sm:hidden">Yeni</span>
            </button>
            <button onClick={fetchData} className="p-2 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
              <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
            </button>
          </div>
        </div>
        
        {/* Tabs */}
        <div className="flex items-center bg-gray-100 rounded-lg p-1 w-fit">
          <button onClick={() => setActiveTab('requests')}
            className={`px-3 sm:px-4 py-1.5 sm:py-2 rounded-md text-xs sm:text-sm font-medium transition-all ${
              activeTab === 'requests' ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}>
            Taleplerim ({pendingQuotes.length})
          </button>
          <button onClick={() => setActiveTab('received')}
            className={`px-3 sm:px-4 py-1.5 sm:py-2 rounded-md text-xs sm:text-sm font-medium transition-all ${
              activeTab === 'received' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}>
            Gelen ({receivedQuotes.length})
          </button>
        </div>
      </div>

      {success && <div className="p-2.5 sm:p-3 bg-emerald-50 border border-emerald-200 rounded-xl text-emerald-600 text-xs sm:text-sm flex items-center gap-2"><CheckCircle className="w-4 h-4 flex-shrink-0" />{success}</div>}

      {displayedQuotes.length === 0 ? (
        <div className="bg-gradient-to-br from-white to-slate-50 rounded-xl sm:rounded-2xl border-2 border-slate-200 p-8 sm:p-12 text-center">
          <FileText className="w-10 h-10 sm:w-12 sm:h-12 text-gray-300 mx-auto mb-3 sm:mb-4" />
          <p className="text-sm sm:text-base text-gray-500 mb-3 sm:mb-4">
            {activeTab === 'requests' ? 'Bekleyen teklif talebiniz yok' : 'Henüz gelen teklif yok'}
          </p>
          {activeTab === 'requests' && (
            <button onClick={() => setShowNewForm(true)} className="px-3 sm:px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-xl text-xs sm:text-sm font-medium inline-flex items-center gap-2">
              <Plus className="w-4 h-4" /> Yeni Talep Oluştur
            </button>
          )}
        </div>
      ) : (
        <div className="space-y-3">
          {displayedQuotes.map((quote) => {
            const status = statusConfig[quote.status] || statusConfig.pending
            return (
              <div key={quote.id} className="bg-gradient-to-br from-white to-slate-50 rounded-xl sm:rounded-2xl border-2 border-slate-200 p-3 sm:p-4 hover:border-slate-300 transition-all">
                <div className="flex items-start gap-2.5 sm:gap-3">
                  <div className={`w-9 h-9 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl flex items-center justify-center flex-shrink-0 ${
                    quote.status === 'accepted' ? 'bg-emerald-100' : 
                    quote.status === 'quoted' ? 'bg-blue-100' :
                    quote.status === 'reviewing' ? 'bg-purple-100' : 
                    quote.status === 'rejected' ? 'bg-red-100' : 
                    quote.status === 'expired' ? 'bg-gray-100' : 'bg-amber-100'
                  }`}>
                    {quote.status === 'accepted' ? <CheckCircle className="w-4 h-4 sm:w-5 sm:h-5 text-emerald-600" /> :
                     quote.status === 'quoted' ? <FileText className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" /> :
                     quote.status === 'reviewing' ? <Eye className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600" /> :
                     quote.status === 'rejected' ? <XCircle className="w-4 h-4 sm:w-5 sm:h-5 text-red-600" /> :
                     <Clock className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600" />}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start sm:items-center gap-2 flex-wrap">
                      <p className="text-sm sm:text-base font-medium text-gray-800 truncate">{quote.company_name}</p>
                      <span className={`px-1.5 sm:px-2 py-0.5 text-[10px] sm:text-xs font-medium rounded-md sm:rounded-lg ${status.bg} ${status.text}`}>{status.label}</span>
                    </div>
                    <p className="text-xs sm:text-sm text-gray-500 mt-0.5">{quote.employee_count} çalışan • {formatDate(quote.created_at)}</p>
                    {quote.requested_services && quote.requested_services.length > 0 && (
                      <p className="text-[10px] sm:text-xs text-gray-400 mt-1 truncate">{getServiceNames(quote.requested_services)}</p>
                    )}
                  </div>
                </div>
                
                {/* Admin yanıtı */}
                {quote.notes && quote.status !== 'pending' && (
                  <div className="mt-2.5 sm:mt-3 pt-2.5 sm:pt-3 border-t border-slate-100">
                    <p className="text-[10px] sm:text-xs text-gray-500"><span className="font-medium">Teklif Detayı:</span> {quote.notes}</p>
                  </div>
                )}
                
                {/* Şirket Aksiyonları - Sadece teklif geldiyse */}
                {quote.status === 'quoted' && (
                  <div className="mt-2.5 sm:mt-3 pt-2.5 sm:pt-3 border-t border-slate-100 flex flex-col sm:flex-row gap-2">
                    <button onClick={() => openQuotePDF(quote)}
                      className="flex-1 py-2 px-3 bg-purple-100 hover:bg-purple-200 text-purple-700 rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-colors flex items-center justify-center gap-1.5">
                      <Eye className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> PDF&apos;i Görüntüle
                    </button>
                    <div className="flex gap-2">
                      <button onClick={() => updateQuoteStatus(quote.id, 'accepted')}
                        className="flex-1 py-2 px-3 bg-emerald-100 hover:bg-emerald-200 text-emerald-700 rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-colors flex items-center justify-center gap-1.5">
                        <CheckCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> Onayla
                      </button>
                      <button onClick={() => updateQuoteStatus(quote.id, 'rejected')}
                        className="py-2 px-3 bg-red-100 hover:bg-red-200 text-red-700 rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-colors">
                        <XCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                      </button>
                    </div>
                  </div>
                )}
                
                {/* İnceleme durumundayken */}
                {quote.status === 'reviewing' && (
                  <div className="mt-2.5 sm:mt-3 pt-2.5 sm:pt-3 border-t border-slate-100 space-y-2">
                    <button onClick={() => openQuotePDF(quote)}
                      className="w-full py-2 px-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-colors flex items-center justify-center gap-1.5">
                      <Eye className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> PDF&apos;i Tekrar Görüntüle
                    </button>
                    <div className="flex gap-2">
                      <button onClick={() => updateQuoteStatus(quote.id, 'accepted')}
                        className="flex-1 py-2 px-3 bg-emerald-500 hover:bg-emerald-600 text-white rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-colors flex items-center justify-center gap-1.5">
                        <CheckCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> Onayla
                      </button>
                      <button onClick={() => updateQuoteStatus(quote.id, 'rejected')}
                        className="flex-1 py-2 px-3 bg-red-500 hover:bg-red-600 text-white rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-colors flex items-center justify-center gap-1.5">
                        <XCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4" /> Reddet
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}

      {showNewForm && (
        <>
          <div className="fixed inset-0 bg-black/20 z-40" onClick={() => setShowNewForm(false)} />
          <div className="fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl z-50 flex flex-col animate-in slide-in-from-right duration-200">
            <div className="flex-shrink-0 p-4 border-b border-slate-100 flex items-center justify-between">
              <h2 className="font-semibold text-gray-800">Yeni Teklif Talebi</h2>
              <button onClick={() => setShowNewForm(false)} className="p-2 hover:bg-slate-100 rounded-lg"><X className="w-5 h-5 text-slate-500" /></button>
            </div>
            <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-4 space-y-4">
              {error && <div className="p-3 bg-red-50 border border-red-200 rounded-xl text-red-600 text-sm flex items-center gap-2"><AlertCircle className="w-4 h-4" />{error}</div>}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-1">Şirket Adı</label>
                  <input type="text" value={formData.companyName} onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400" required />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-1">Çalışan</label>
                  <input type="number" value={formData.employeeCount} onChange={(e) => setFormData({ ...formData, employeeCount: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400" required min="1" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-600 mb-1.5">Tehlike Sınıfı</label>
                <div className="grid grid-cols-3 gap-2">
                  {tehlikeSiniflari.map(t => {
                    const isSelected = formData.tehlikeSinifi === t.value
                    const colorClasses = {
                      emerald: isSelected ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-slate-200 hover:border-emerald-300',
                      amber: isSelected ? 'border-amber-500 bg-amber-50 text-amber-700' : 'border-slate-200 hover:border-amber-300',
                      red: isSelected ? 'border-red-500 bg-red-50 text-red-700' : 'border-slate-200 hover:border-red-300',
                    }
                    return (
                      <button key={t.value} type="button" onClick={() => setFormData({ ...formData, tehlikeSinifi: t.value })}
                        className={`py-2 px-2 rounded-xl text-xs font-medium transition-all border-2 ${colorClasses[t.color as keyof typeof colorClasses]}`}>{t.label}</button>
                    )
                  })}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-600 mb-1.5">Hizmetler ({formData.selectedServices.length})</label>
                <div className="space-y-2">
                  {serviceTypes.map(h => (
                    <button key={h.id} type="button" onClick={() => toggleService(h.id)}
                      className={`w-full py-2 px-3 rounded-xl text-sm font-medium transition-all border-2 text-left flex items-center gap-2 ${
                        formData.selectedServices.includes(h.id) ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-slate-200 text-gray-600 hover:border-slate-300'
                      }`}>
                      <div className={`w-4 h-4 rounded border-2 flex items-center justify-center flex-shrink-0 ${formData.selectedServices.includes(h.id) ? 'border-blue-500 bg-blue-500' : 'border-slate-300'}`}>
                        {formData.selectedServices.includes(h.id) && <svg className="w-2.5 h-2.5 text-white" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /></svg>}
                      </div>
                      {h.name}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-600 mb-1">Notlar</label>
                <textarea value={formData.notes} onChange={(e) => setFormData({ ...formData, notes: e.target.value })} rows={2}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 resize-none" placeholder="Varsa notlarınız..." />
              </div>
            </form>
            <div className="flex-shrink-0 p-4 border-t border-slate-100">
              <button type="submit" onClick={handleSubmit} disabled={isSubmitting || formData.selectedServices.length === 0 || !formData.tehlikeSinifi}
                className="w-full flex items-center justify-center gap-2 py-3 bg-blue-500 hover:bg-blue-600 disabled:bg-slate-300 disabled:cursor-not-allowed text-white rounded-xl font-medium transition-colors">
                {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                {isSubmitting ? 'Gönderiliyor...' : 'Teklif Talep Et'}
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  )
}
