"use client"

import { useState, useEffect } from 'react'
import { 
  ClipboardList, Calendar, Loader2, RefreshCw, Banknote,
  Shield, Stethoscope, FileSearch, GraduationCap, Truck, Users, Activity, Clipboard
} from 'lucide-react'
import { useAuth } from '@/lib/auth/AuthProvider'
import { getSupabaseClient } from '@/lib/supabase/client'

interface CompanyService {
  id: string
  status: string
  start_date: string | null
  price: number | null
  notes: string | null
  created_at: string
  service_types?: { name: string; category: string; description: string }
}

const statusConfig: Record<string, { label: string; bg: string; text: string }> = {
  active: { label: 'Aktif', bg: 'bg-emerald-100', text: 'text-emerald-700' },
  pending: { label: 'Beklemede', bg: 'bg-amber-100', text: 'text-amber-700' },
  completed: { label: 'Tamamlandı', bg: 'bg-blue-100', text: 'text-blue-700' },
  cancelled: { label: 'İptal', bg: 'bg-red-100', text: 'text-red-700' },
}

// Hizmet adına göre ikon eşleştirme
const getServiceIcon = (name: string) => {
  const lower = name.toLowerCase()
  if (lower.includes('güvenlik') || lower.includes('isg')) return Shield
  if (lower.includes('hekim') || lower.includes('sağlık')) return Stethoscope
  if (lower.includes('risk') || lower.includes('analiz')) return FileSearch
  if (lower.includes('eğitim')) return GraduationCap
  if (lower.includes('mobil')) return Truck
  if (lower.includes('personel') || lower.includes('diğer')) return Users
  if (lower.includes('periyodik') || lower.includes('kontrol')) return Activity
  return Clipboard
}

// Hizmet adına göre renk
const getServiceColor = (name: string, status: string) => {
  if (status !== 'active') return { bg: 'bg-slate-100', icon: 'text-slate-500' }
  
  const lower = name.toLowerCase()
  if (lower.includes('güvenlik') || lower.includes('isg')) return { bg: 'bg-blue-100', icon: 'text-blue-600' }
  if (lower.includes('hekim') || lower.includes('sağlık')) return { bg: 'bg-emerald-100', icon: 'text-emerald-600' }
  if (lower.includes('risk') || lower.includes('analiz')) return { bg: 'bg-amber-100', icon: 'text-amber-600' }
  if (lower.includes('eğitim')) return { bg: 'bg-purple-100', icon: 'text-purple-600' }
  if (lower.includes('mobil')) return { bg: 'bg-cyan-100', icon: 'text-cyan-600' }
  if (lower.includes('personel') || lower.includes('diğer')) return { bg: 'bg-pink-100', icon: 'text-pink-600' }
  if (lower.includes('periyodik') || lower.includes('kontrol')) return { bg: 'bg-orange-100', icon: 'text-orange-600' }
  return { bg: 'bg-slate-100', icon: 'text-slate-600' }
}

export default function PortalHizmetlerPage() {
  const { user } = useAuth()
  const [services, setServices] = useState<CompanyService[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const fetchServices = async (isRefresh = false) => {
    if (!user) return
    if (isRefresh) setRefreshing(true)
    else setLoading(true)
    
    const supabase = getSupabaseClient()
    
    // 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) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data } = await (supabase as any)
        .from('company_services')
        .select('id, status, start_date, price, notes, created_at, service_types(name, category, description)')
        .eq('company_id', company.id)
        .order('created_at', { ascending: false })

      if (data) setServices(data)
    }
    
    setLoading(false)
    setRefreshing(false)
  }

  useEffect(() => { if (user) fetchServices() }, [user])

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleDateString('tr-TR', { day: '2-digit', month: '2-digit', year: 'numeric' })
  }

  const formatPrice = (price: number | null) => {
    if (!price) return '-'
    return price.toLocaleString('tr-TR') + ' ₺/ay'
  }

  const activeCount = services.filter(s => s.status === 'active').length

  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 items-center justify-between">
        <h1 className="text-lg sm:text-xl font-semibold text-gray-800">Hizmetlerim</h1>
        <button onClick={() => fetchServices(true)} disabled={refreshing}
          className="p-2 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors disabled:opacity-50">
          <RefreshCw className={`w-5 h-5 ${refreshing ? 'animate-spin' : ''}`} />
        </button>
      </div>

      {/* Aktif hizmet sayısı */}
      {services.length > 0 && (
        <div className="flex items-center gap-2">
          <span className="text-xs sm:text-sm text-gray-500">{activeCount} aktif hizmet</span>
        </div>
      )}

      {services.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">
          <ClipboardList 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">Henüz atanmış hizmet bulunmuyor</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
          {services.map((service) => {
            const status = statusConfig[service.status] || statusConfig.pending
            const serviceName = service.service_types?.name || 'Hizmet'
            const Icon = getServiceIcon(serviceName)
            const colors = getServiceColor(serviceName, service.status)
            const isCancelled = service.status === 'cancelled'

            return (
              <div key={service.id}
                className={`bg-gradient-to-br from-white to-slate-50 rounded-xl sm:rounded-2xl border-2 p-3 sm:p-4 transition-all group ${
                  isCancelled 
                    ? 'border-red-300 bg-red-50/30' 
                    : 'border-slate-200 hover:border-blue-400 hover:shadow-lg'
                }`}
              >
                {/* Üst Kısım - İkon ve Durum */}
                <div className="flex items-start justify-between mb-2 sm:mb-3">
                  <div className={`w-10 h-10 sm:w-12 sm:h-12 rounded-lg sm:rounded-xl ${isCancelled ? 'bg-red-100' : colors.bg} flex items-center justify-center`}>
                    <Icon className={`w-5 h-5 sm:w-6 sm:h-6 ${isCancelled ? 'text-red-500' : colors.icon}`} />
                  </div>
                  <span className={`px-1.5 sm:px-2 py-0.5 sm:py-1 text-[10px] sm:text-xs font-medium rounded-md sm:rounded-lg ${status.bg} ${status.text}`}>
                    {status.label}
                  </span>
                </div>

                {/* Hizmet Adı */}
                <h3 className={`font-semibold text-xs sm:text-sm leading-tight mb-1 line-clamp-2 ${isCancelled ? 'text-gray-400 line-through' : 'text-gray-800'}`}>
                  {serviceName}
                </h3>
                
                {/* Açıklama - sadece desktop'ta göster */}
                {service.service_types?.description && (
                  <p className="text-[10px] sm:text-xs text-gray-400 line-clamp-2 mb-2 sm:mb-3 hidden sm:block">
                    {service.service_types.description}
                  </p>
                )}

                {/* Fiyat ve Tarih */}
                <div className="pt-2 sm:pt-3 border-t border-slate-100 space-y-1 sm:space-y-1.5">
                  {/* Fiyat */}
                  <div className="flex items-center justify-between text-[10px] sm:text-xs">
                    <span className="text-gray-400 flex items-center gap-1">
                      <Banknote className="w-3 h-3" /> Fiyat
                    </span>
                    <span className={`font-semibold ${isCancelled ? 'text-gray-400' : 'text-emerald-600'}`}>
                      {formatPrice(service.price)}
                    </span>
                  </div>
                  {/* Başlangıç Tarihi */}
                  <div className="flex items-center justify-between text-[10px] sm:text-xs">
                    <span className="text-gray-400 flex items-center gap-1">
                      <Calendar className="w-3 h-3" /> Başlangıç
                    </span>
                    <span className="text-gray-600 font-medium">{formatDate(service.start_date)}</span>
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}
