"use client"

import { useState, useEffect, useCallback, useRef } from 'react'
import { 
  Search, Plus, Building2, Users, Mail, Phone, MapPin,
  MoreVertical, Edit, Eye, RefreshCw, Loader2, X, Check, Copy,
  MessageSquare, Power, AlertTriangle, Send, ChevronLeft, ChevronRight
} 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 Company {
  id: string
  company_name: string
  email: string
  phone: string | null
  employee_count: number | null
  tehlike_sinifi: string | null
  city: string | null
  is_active: boolean
  profile_id: string | null
  created_at: string
}

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 ITEMS_PER_PAGE = 10

export default function SirketlerPage() {
  const { user } = useAuth()
  const [companies, setCompanies] = useState<Company[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const [showAddModal, setShowAddModal] = useState(false)
  const [selectedCompany, setSelectedCompany] = useState<Company | null>(null)
  const [showDetailModal, setShowDetailModal] = useState(false)
  const [showMessageModal, setShowMessageModal] = useState(false)
  const [editMode, setEditMode] = useState(false)
  const [menuOpen, setMenuOpen] = useState<string | null>(null)
  const [menuPosition, setMenuPosition] = useState<'top' | 'bottom'>('bottom')
  const menuButtonRef = useRef<HTMLButtonElement>(null)
  const [submitting, setSubmitting] = useState(false)
  const [createdCredentials, setCreatedCredentials] = useState<{email: string, password: string} | null>(null)
  const [error, setError] = useState('')
  const [message, setMessage] = useState({ subject: '', content: '' })
  
  const [formData, setFormData] = useState({
    companyName: '', email: '', phone: '', password: '',
    employeeCount: '', tehlikeSinifi: 'az_tehlikeli', city: '', contactPerson: ''
  })

  const supabase = getSupabaseClient()

  const fetchCompanies = useCallback(async () => {
    if (!user) return
    setLoading(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data, error } = await (supabase as any)
        .from('companies').select('*').order('created_at', { ascending: false })
      if (error) throw error
      if (data) setCompanies(data)
    } catch (err) { console.error('Fetch error:', err) }
    setLoading(false)
  }, [user, supabase])

  useEffect(() => { if (user) fetchCompanies() }, [user, fetchCompanies])
  useVisibilityRefresh(fetchCompanies, !!user)

  const generatePassword = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
    let password = ''
    for (let i = 0; i < 10; i++) password += chars.charAt(Math.floor(Math.random() * chars.length))
    setFormData(prev => ({ ...prev, password }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setSubmitting(true)
    try {
      const response = await fetch('/api/admin/create-company', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          companyName: formData.companyName, email: formData.email, phone: formData.phone,
          password: formData.password, employeeCount: parseInt(formData.employeeCount) || 0,
          tehlikeSinifi: formData.tehlikeSinifi, city: formData.city, contactPerson: formData.contactPerson
        }),
      })
      const result = await response.json()
      if (!response.ok) throw new Error(result.error || 'Bir hata oluştu')
      setCreatedCredentials({ email: formData.email, password: formData.password })
      fetchCompanies()
    } catch (err) { setError(err instanceof Error ? err.message : 'Bir hata oluştu') }
    setSubmitting(false)
  }

  const toggleCompanyStatus = async (company: Company) => {
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { error } = await (supabase as any)
        .from('companies').update({ is_active: !company.is_active }).eq('id', company.id)
      if (!error) {
        setCompanies(prev => prev.map(c => c.id === company.id ? { ...c, is_active: !c.is_active } : c))
        if (selectedCompany?.id === company.id) setSelectedCompany({ ...selectedCompany, is_active: !company.is_active })
      }
    } catch (err) { console.error('Toggle error:', err) }
    setMenuOpen(null)
  }

  const updateCompany = async () => {
    if (!selectedCompany) return
    setSubmitting(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { error } = await (supabase as any)
        .from('companies').update({
          company_name: formData.companyName, phone: formData.phone,
          employee_count: parseInt(formData.employeeCount) || 0,
          tehlike_sinifi: formData.tehlikeSinifi, city: formData.city
        }).eq('id', selectedCompany.id)
      if (!error) {
        fetchCompanies()
        setEditMode(false)
        setShowDetailModal(false)
      }
    } catch (err) { console.error('Update error:', err) }
    setSubmitting(false)
  }

  const sendMessage = async () => {
    if (!selectedCompany || !message.subject || !message.content) return
    setSubmitting(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { error } = await (supabase as any).from('messages').insert({
        company_id: selectedCompany.id, subject: message.subject,
        content: message.content, sender_type: 'admin', sender_id: user?.id
      })
      if (!error) {
        setMessage({ subject: '', content: '' })
        setShowMessageModal(false)
        alert('Mesaj gönderildi!')
      }
    } catch (err) { console.error('Message error:', err) }
    setSubmitting(false)
  }

  const openDetail = (company: Company) => {
    setSelectedCompany(company)
    setFormData({
      companyName: company.company_name, email: company.email, phone: company.phone || '',
      password: '', employeeCount: company.employee_count?.toString() || '',
      tehlikeSinifi: company.tehlike_sinifi || 'az_tehlikeli', city: company.city || '', contactPerson: ''
    })
    setEditMode(false)
    setShowDetailModal(true)
  }

  const resetForm = () => {
    setFormData({ companyName: '', email: '', phone: '', password: '', employeeCount: '', tehlikeSinifi: 'az_tehlikeli', city: '', contactPerson: '' })
    setCreatedCredentials(null)
    setError('')
  }

  const filtered = companies.filter(c => {
    const matchesSearch = c.company_name.toLowerCase().includes(search.toLowerCase()) ||
                          c.email.toLowerCase().includes(search.toLowerCase())
    const matchesStatus = statusFilter === 'all' || 
      (statusFilter === 'active' && c.is_active) || 
      (statusFilter === 'inactive' && !c.is_active)
    return matchesSearch && matchesStatus
  })

  // Pagination
  const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE)
  const paginatedCompanies = filtered.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE)

  // Reset page when filter changes
  useEffect(() => { setCurrentPage(1) }, [search, statusFilter])

  const activeCount = companies.filter(c => c.is_active).length
  const inactiveCount = companies.filter(c => !c.is_active).length

  const formatDate = (dateStr: string) => new Date(dateStr).toLocaleDateString('tr-TR')

  const handleMenuOpen = (companyId: string, event: React.MouseEvent<HTMLButtonElement>) => {
    const button = event.currentTarget
    const rect = button.getBoundingClientRect()
    const spaceBelow = window.innerHeight - rect.bottom
    setMenuPosition(spaceBelow < 120 ? 'top' : 'bottom')
    setMenuOpen(menuOpen === companyId ? null : companyId)
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <h1 className="page-title">Şirketler</h1>
        <div className="flex items-center gap-3">
          <button onClick={fetchCompanies} disabled={loading}
            className="p-2.5 bg-white border border-gray-200 hover:bg-gray-50 text-gray-500 rounded-xl transition-colors disabled:opacity-50">
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          </button>
          <button onClick={() => { resetForm(); setShowAddModal(true) }}
            className="flex items-center gap-2 px-4 py-2.5 bg-blue-500 hover:bg-blue-600 text-white rounded-xl font-medium transition-colors">
            <Plus className="w-4 h-4" /> Yeni Şirket
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col 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 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="flex items-center bg-gray-100 rounded-lg p-1 overflow-x-auto">
          <button onClick={() => setStatusFilter('all')}
            className={`px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all whitespace-nowrap ${statusFilter === 'all' ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500'}`}>
            Tümü ({companies.length})
          </button>
          <button onClick={() => setStatusFilter('active')}
            className={`px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all whitespace-nowrap ${statusFilter === 'active' ? 'bg-white text-emerald-600 shadow-sm' : 'text-gray-500'}`}>
            Aktif ({activeCount})
          </button>
          <button onClick={() => setStatusFilter('inactive')}
            className={`px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all whitespace-nowrap ${statusFilter === 'inactive' ? 'bg-white text-red-600 shadow-sm' : 'text-gray-500'}`}>
            Pasif ({inactiveCount})
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {loading && companies.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">
            <Building2 className="w-10 h-10 text-gray-200 mx-auto mb-2" />
            <p className="text-gray-400 text-sm">Şirket bulunamadı</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[700px]">
              <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 hidden md:table-cell">İletişim</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider hidden sm:table-cell">Ç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 sm:table-cell">Kayıt</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">
                {paginatedCompanies.map((company) => {
                  const tehlike = company.tehlike_sinifi ? tehlikeConfig[company.tehlike_sinifi] : null
                  return (
                    <tr key={company.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 flex items-center justify-center flex-shrink-0 ${company.is_active ? 'bg-blue-50' : 'bg-gray-100'}`}>
                            <Building2 className={`w-4 h-4 ${company.is_active ? 'text-blue-500' : 'text-gray-400'}`} />
                          </div>
                          <div className="min-w-0">
                            <p className="text-sm font-medium text-gray-800 truncate">{company.company_name}</p>
                            {company.city && <p className="text-xs text-gray-400 flex items-center gap-1"><MapPin className="w-3 h-3" />{company.city}</p>}
                            {/* Mobile'da ek bilgiler */}
                            <div className="flex flex-wrap items-center gap-2 mt-1 sm:hidden">
                              <span className="text-xs text-gray-500 flex items-center gap-1">
                                <Users className="w-3 h-3" /> {company.employee_count || '-'}
                              </span>
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-4 hidden md:table-cell">
                        <div className="space-y-1">
                          <p className="text-sm text-gray-600 flex items-center gap-1.5 truncate max-w-[200px]"><Mail className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />{company.email}</p>
                          {company.phone && <p className="text-xs text-gray-400 flex items-center gap-1.5"><Phone className="w-3 h-3" />{company.phone}</p>}
                        </div>
                      </td>
                      <td className="px-4 py-4 hidden sm:table-cell">
                        <div className="flex items-center gap-1.5 text-sm text-gray-600">
                          <Users className="w-4 h-4 text-gray-400" /> {company.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 ${
                          company.is_active ? 'bg-emerald-50 text-emerald-600' : 'bg-gray-100 text-gray-500'
                        }`}>{company.is_active ? 'Aktif' : 'Pasif'}</span>
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-400 hidden sm:table-cell">{formatDate(company.created_at)}</td>
                      <td className="px-4 py-4">
                        <div className="flex items-center justify-end gap-1">
                          <button onClick={() => { setSelectedCompany(company); setShowMessageModal(true) }} title="Mesaj Gönder"
                            className="p-2 text-gray-400 hover:text-purple-500 hover:bg-purple-50 rounded-lg transition-colors sm:opacity-0 sm:group-hover:opacity-100">
                            <MessageSquare className="w-4 h-4" />
                          </button>
                          <button onClick={() => openDetail(company)} title="Detay"
                            className="p-2 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-lg transition-colors sm:opacity-0 sm:group-hover:opacity-100">
                            <Eye className="w-4 h-4" />
                          </button>
                          <div className="relative">
                            <button onClick={(e) => handleMenuOpen(company.id, e)}
                              className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                              <MoreVertical className="w-4 h-4" />
                            </button>
                            {menuOpen === company.id && (
                              <div className={`absolute right-0 w-40 bg-white rounded-xl shadow-lg border border-gray-100 py-1 z-20 ${
                                menuPosition === 'top' ? 'bottom-full mb-1' : 'top-full mt-1'
                              }`}>
                                <button onClick={() => { openDetail(company); setEditMode(true); setMenuOpen(null) }}
                                  className="flex items-center gap-2 w-full px-3 py-2 text-sm text-gray-600 hover:bg-gray-50">
                                  <Edit className="w-4 h-4" /> Düzenle
                                </button>
                                <button onClick={() => toggleCompanyStatus(company)}
                                  className={`flex items-center gap-2 w-full px-3 py-2 text-sm ${company.is_active ? 'text-red-500 hover:bg-red-50' : 'text-emerald-500 hover:bg-emerald-50'}`}>
                                  <Power className="w-4 h-4" /> {company.is_active ? 'Pasife Al' : 'Aktif Et'}
                                </button>
                              </div>
                            )}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
        
        {/* Pagination */}
        {totalPages > 1 && (
          <div className="px-4 py-3 border-t border-gray-100 flex flex-col sm:flex-row items-center justify-between gap-3">
            <p className="text-sm text-gray-500 order-2 sm:order-1">
              {filtered.length} şirketten {(currentPage - 1) * ITEMS_PER_PAGE + 1}-{Math.min(currentPage * ITEMS_PER_PAGE, filtered.length)} arası
            </p>
            <div className="flex items-center gap-1 order-1 sm:order-2">
              <button onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1}
                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                <ChevronLeft className="w-4 h-4" />
              </button>
              {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                <button key={page} onClick={() => setCurrentPage(page)}
                  className={`w-8 h-8 rounded-lg text-sm font-medium transition-colors ${
                    currentPage === page ? 'bg-blue-500 text-white' : 'text-gray-600 hover:bg-gray-100'
                  }`}>
                  {page}
                </button>
              ))}
              <button onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages}
                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Add Company Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => setShowAddModal(false)}>
          <div onClick={(e) => e.stopPropagation()} className="bg-white rounded-2xl w-full max-w-lg border border-gray-200 shadow-xl max-h-[90vh] overflow-y-auto">
            <div className="p-5 border-b border-gray-100 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-800">Yeni Şirket Ekle</h2>
              <button onClick={() => setShowAddModal(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>
            
            {createdCredentials ? (
              <div className="p-5 space-y-4">
                <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4 text-center">
                  <Check className="w-10 h-10 text-emerald-500 mx-auto mb-2" />
                  <p className="text-emerald-700 font-medium">Şirket başarıyla oluşturuldu!</p>
                </div>
                <div className="bg-gray-50 rounded-xl p-4 space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">E-posta:</span>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium">{createdCredentials.email}</span>
                      <button onClick={() => navigator.clipboard.writeText(createdCredentials.email)} className="p-1 hover:bg-gray-200 rounded"><Copy className="w-4 h-4 text-gray-400" /></button>
                    </div>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">Şifre:</span>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium font-mono">{createdCredentials.password}</span>
                      <button onClick={() => navigator.clipboard.writeText(createdCredentials.password)} className="p-1 hover:bg-gray-200 rounded"><Copy className="w-4 h-4 text-gray-400" /></button>
                    </div>
                  </div>
                </div>
                <button onClick={() => setShowAddModal(false)} className="w-full px-4 py-2.5 bg-blue-500 hover:bg-blue-600 text-white rounded-xl font-medium">Tamam</button>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="p-5 space-y-4">
                {error && <div className="bg-red-50 border border-red-200 rounded-xl p-3 flex items-center gap-2 text-red-600 text-sm"><AlertTriangle className="w-4 h-4" />{error}</div>}
                
                {/* Şirket Adı - Tam genişlik */}
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-1.5">Şirket Adı *</label>
                  <input type="text" required value={formData.companyName} onChange={(e) => setFormData(p => ({ ...p, companyName: e.target.value }))}
                    className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                </div>

                {/* E-posta ve Telefon */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-600 mb-1.5">E-posta *</label>
                    <input type="email" required value={formData.email} onChange={(e) => setFormData(p => ({ ...p, email: e.target.value }))}
                      className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 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">Telefon</label>
                    <input type="tel" value={formData.phone} onChange={(e) => setFormData(p => ({ ...p, phone: e.target.value }))}
                      className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                  </div>
                </div>

                {/* Şifre - Tam genişlik */}
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-1.5">Şifre *</label>
                  <div className="flex gap-2">
                    <input type="text" required value={formData.password} onChange={(e) => setFormData(p => ({ ...p, password: e.target.value }))}
                      className="flex-1 px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 font-mono focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                    <button type="button" onClick={generatePassword} className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-600 rounded-xl text-sm font-medium whitespace-nowrap">Oluştur</button>
                  </div>
                </div>

                {/* Çalışan Sayısı ve Tehlike Sınıfı */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-600 mb-1.5">Çalışan Sayısı</label>
                    <input type="number" value={formData.employeeCount} onChange={(e) => setFormData(p => ({ ...p, employeeCount: e.target.value }))}
                      className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 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="tehlikeSinifi"
                      value={formData.tehlikeSinifi}
                      onChange={(e) => setFormData(p => ({ ...p, tehlikeSinifi: e.target.value }))}
                      placeholder="Seçiniz"
                      variant="admin"
                      options={[
                        { value: 'az_tehlikeli', label: 'Az Tehlikeli' },
                        { value: 'tehlikeli', label: 'Tehlikeli' },
                        { value: 'cok_tehlikeli', label: 'Çok Tehlikeli' },
                      ]}
                    />
                  </div>
                </div>

                {/* Şehir - Tam genişlik */}
                <div>
                  <label className="block text-sm font-medium text-gray-600 mb-1.5">Şehir</label>
                  <input type="text" value={formData.city} onChange={(e) => setFormData(p => ({ ...p, city: e.target.value }))}
                    className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                </div>

                <div className="flex gap-3 pt-2">
                  <button type="button" onClick={() => setShowAddModal(false)} className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-medium">İptal</button>
                  <button type="submit" disabled={submitting} className="flex-1 px-4 py-2.5 bg-blue-500 hover:bg-blue-600 text-white rounded-xl font-medium disabled:opacity-50 flex items-center justify-center gap-2">
                    {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />} Oluştur
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}

      {/* Detail/Edit Modal */}
      {showDetailModal && selectedCompany && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => setShowDetailModal(false)}>
          <div onClick={(e) => e.stopPropagation()} className="bg-white rounded-2xl w-full max-w-lg border border-gray-200 shadow-xl max-h-[90vh] overflow-y-auto">
            <div className="p-5 border-b border-gray-100 flex items-center justify-between">
              <div>
                <h2 className="text-lg font-semibold text-gray-800">{editMode ? 'Şirketi Düzenle' : 'Şirket Detayı'}</h2>
                <p className="text-gray-400 text-sm">{selectedCompany.email}</p>
              </div>
              <div className="flex items-center gap-2">
                {!editMode && (
                  <button onClick={() => setEditMode(true)} className="p-2 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-lg">
                    <Edit className="w-5 h-5" />
                  </button>
                )}
                <button onClick={() => setShowDetailModal(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>
            
            <div className="p-5 space-y-4">
              {editMode ? (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-600 mb-1.5">Şirket Adı</label>
                    <input type="text" value={formData.companyName} onChange={(e) => setFormData(p => ({ ...p, companyName: e.target.value }))}
                      className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-600 mb-1.5">Telefon</label>
                      <input type="tel" value={formData.phone} onChange={(e) => setFormData(p => ({ ...p, phone: e.target.value }))}
                        className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 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">Çalışan Sayısı</label>
                      <input type="number" value={formData.employeeCount} onChange={(e) => setFormData(p => ({ ...p, employeeCount: e.target.value }))}
                        className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 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="tehlikeSinifi"
                        value={formData.tehlikeSinifi}
                        onChange={(e) => setFormData(p => ({ ...p, tehlikeSinifi: e.target.value }))}
                        placeholder="Seçiniz"
                        variant="admin"
                        options={[
                          { value: 'az_tehlikeli', label: 'Az Tehlikeli' },
                          { value: 'tehlikeli', label: 'Tehlikeli' },
                          { value: 'cok_tehlikeli', label: 'Çok Tehlikeli' },
                        ]}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-600 mb-1.5">Şehir</label>
                      <input type="text" value={formData.city} onChange={(e) => setFormData(p => ({ ...p, city: e.target.value }))}
                        className="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20" />
                    </div>
                  </div>
                </>
              ) : (
                <>
                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                    <div className="flex items-center gap-3">
                      <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${selectedCompany.is_active ? 'bg-blue-100' : 'bg-gray-200'}`}>
                        <Building2 className={`w-5 h-5 ${selectedCompany.is_active ? 'text-blue-500' : 'text-gray-400'}`} />
                      </div>
                      <div>
                        <p className="font-medium text-gray-800">{selectedCompany.company_name}</p>
                        <p className="text-xs text-gray-400">{selectedCompany.city || 'Şehir belirtilmemiş'}</p>
                      </div>
                    </div>
                    <span className={`px-3 py-1 text-xs font-medium rounded-lg ${selectedCompany.is_active ? 'bg-emerald-100 text-emerald-600' : 'bg-gray-200 text-gray-500'}`}>
                      {selectedCompany.is_active ? 'Aktif' : 'Pasif'}
                    </span>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div className="bg-gray-50 rounded-xl p-3">
                      <p className="text-[10px] text-gray-400 uppercase tracking-wider mb-1">E-posta</p>
                      <p className="text-sm text-gray-700">{selectedCompany.email}</p>
                    </div>
                    <div className="bg-gray-50 rounded-xl p-3">
                      <p className="text-[10px] text-gray-400 uppercase tracking-wider mb-1">Telefon</p>
                      <p className="text-sm text-gray-700">{selectedCompany.phone || '-'}</p>
                    </div>
                    <div className="bg-gray-50 rounded-xl p-3">
                      <p className="text-[10px] text-gray-400 uppercase tracking-wider mb-1">Çalışan</p>
                      <p className="text-sm text-gray-700">{selectedCompany.employee_count || '-'}</p>
                    </div>
                    <div className="bg-gray-50 rounded-xl p-3">
                      <p className="text-[10px] text-gray-400 uppercase tracking-wider mb-1">Tehlike</p>
                      <p className="text-sm text-gray-700">{selectedCompany.tehlike_sinifi ? tehlikeConfig[selectedCompany.tehlike_sinifi]?.label : '-'}</p>
                    </div>
                  </div>
                  <p className="text-xs text-gray-400">Kayıt: {formatDate(selectedCompany.created_at)}</p>
                </>
              )}
            </div>
            
            <div className="p-5 border-t border-gray-100 flex gap-3">
              {editMode ? (
                <>
                  <button onClick={() => setEditMode(false)} className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-medium">İptal</button>
                  <button onClick={updateCompany} disabled={submitting} className="flex-1 px-4 py-2.5 bg-blue-500 hover:bg-blue-600 text-white rounded-xl font-medium disabled:opacity-50 flex items-center justify-center gap-2">
                    {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />} Kaydet
                  </button>
                </>
              ) : (
                <>
                  <button onClick={() => toggleCompanyStatus(selectedCompany)}
                    className={`flex-1 px-4 py-2.5 rounded-xl font-medium flex items-center justify-center gap-2 ${
                      selectedCompany.is_active ? 'bg-red-50 hover:bg-red-100 text-red-600' : 'bg-emerald-50 hover:bg-emerald-100 text-emerald-600'
                    }`}>
                    <Power className="w-4 h-4" /> {selectedCompany.is_active ? 'Pasife Al' : 'Aktif Et'}
                  </button>
                  <button onClick={() => { setShowDetailModal(false); setShowMessageModal(true) }}
                    className="flex-1 px-4 py-2.5 bg-purple-500 hover:bg-purple-600 text-white rounded-xl font-medium flex items-center justify-center gap-2">
                    <MessageSquare className="w-4 h-4" /> Mesaj Gönder
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Message Modal */}
      {showMessageModal && selectedCompany && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => setShowMessageModal(false)}>
          <div onClick={(e) => e.stopPropagation()} className="bg-white rounded-2xl w-full max-w-lg border border-gray-200 shadow-xl max-h-[90vh] overflow-y-auto">
            <div className="p-5 border-b border-gray-100 flex items-center justify-between">
              <div>
                <h2 className="text-lg font-semibold text-gray-800">Mesaj Gönder</h2>
                <p className="text-gray-400 text-sm">{selectedCompany.company_name}</p>
              </div>
              <button onClick={() => setShowMessageModal(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">
              <div>
                <label className="block text-sm font-medium text-gray-600 mb-1.5">Konu *</label>
                <input type="text" value={message.subject} onChange={(e) => setMessage(p => ({ ...p, subject: e.target.value }))}
                  placeholder="Mesaj konusu..."
                  className="w-full px-3 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-purple-500/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-600 mb-1.5">Mesaj *</label>
                <textarea value={message.content} onChange={(e) => setMessage(p => ({ ...p, content: e.target.value }))}
                  placeholder="Mesajınızı yazın..." rows={5}
                  className="w-full px-3 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-purple-500/20 resize-none" />
              </div>
              <p className="text-xs text-gray-400">Bu mesaj şirketin portal mesajlar bölümünde görünecektir.</p>
            </div>
            
            <div className="p-5 border-t border-gray-100 flex gap-3">
              <button onClick={() => setShowMessageModal(false)} className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-medium">İptal</button>
              <button onClick={sendMessage} disabled={submitting || !message.subject || !message.content}
                className="flex-1 px-4 py-2.5 bg-purple-500 hover:bg-purple-600 text-white rounded-xl font-medium disabled:opacity-50 flex items-center justify-center gap-2">
                {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />} Gönder
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Click outside to close menu */}
      {menuOpen && <div className="fixed inset-0 z-0" onClick={() => setMenuOpen(null)} />}
    </div>
  )
}
