"use client"

import { useState, useEffect, useRef, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { 
  Search, Upload, FileText, Building2, Download, Eye, Trash2, 
  RefreshCw, Loader2, X, AlertCircle, CheckCircle, ChevronDown, Calendar
} 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
}

interface Document {
  id: string
  company_id: string
  document_type: string
  title: string
  description: string | null
  file_url: string | null
  file_name: string | null
  file_size: number | null
  status: string
  valid_from: string | null
  valid_until: string | null
  created_at: string
  companies?: { company_name: string }
}

interface GroupedDocuments {
  company: Company
  documents: Document[]
}

const typeLabels: Record<string, string> = {
  sozlesme: 'Sözleşme',
  yetki_belgesi: 'Yetki Belgesi',
  sertifika: 'Sertifika',
  egitim_belgesi: 'Eğitim Belgesi',
  saglik_raporu: 'Sağlık Raporu',
  risk_raporu: 'Risk Raporu',
  acil_durum_plani: 'Acil Durum Planı',
  denetim_raporu: 'Denetim Raporu',
  diger: 'Diğer'
}

const statusLabels: Record<string, { label: string; color: string }> = {
  draft: { label: 'Taslak', color: 'slate' },
  pending_signature: { label: 'İmza Bekliyor', color: 'amber' },
  signed: { label: 'İmzalandı', color: 'green' },
  archived: { label: 'Arşiv', color: 'blue' }
}

export default function BelgelerPage() {
  const { isLoading: authLoading, user } = useAuth()
  const [documents, setDocuments] = useState<Document[]>([])
  const [companies, setCompanies] = useState<Company[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [showUpload, setShowUpload] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [expandedCompanies, setExpandedCompanies] = useState<Set<string>>(new Set())
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [formData, setFormData] = useState({
    companyId: '',
    documentType: 'sozlesme',
    title: '',
    description: '',
    status: 'signed',
    validFrom: '',
    validUntil: ''
  })

  const supabase = getSupabaseClient()

  const fetchData = async () => {
    if (!user) return
    setLoading(true)
    
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data: docsData, error: docsError } = await (supabase as any)
        .from('documents')
        .select('*, companies(company_name)')
        .order('created_at', { ascending: false })
      
      if (docsError) throw docsError
      if (docsData) setDocuments(docsData)

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data: companiesData, error: companiesError } = await (supabase as any)
        .from('companies')
        .select('id, company_name')
        .eq('is_active', true)
        .order('company_name')
      
      if (companiesError) throw companiesError
      if (companiesData) setCompanies(companiesData)
    } catch (err) {
      console.error('Fetch error:', err)
    }

    setLoading(false)
  }

  useEffect(() => {
    if (user) {
      fetchData()
    }
  }, [user])

  // Şirketlere göre grupla - tüm şirketler (belgesi olsun olmasın)
  const groupedDocuments: GroupedDocuments[] = companies
    .map(company => ({
      company,
      documents: documents.filter(d => d.company_id === company.id)
    }))
    .filter(group => {
      if (!search) return true
      const matchesCompany = group.company.company_name.toLowerCase().includes(search.toLowerCase())
      const matchesDoc = group.documents.some(d => 
        d.title.toLowerCase().includes(search.toLowerCase())
      )
      return matchesCompany || matchesDoc
    })

  const toggleCompany = (companyId: string) => {
    setExpandedCompanies(prev => {
      const newSet = new Set(prev)
      if (newSet.has(companyId)) {
        newSet.delete(companyId)
      } else {
        newSet.add(companyId)
      }
      return newSet
    })
  }

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      if (file.size > 10 * 1024 * 1024) {
        setError('Dosya boyutu 10MB\'dan küçük olmalı')
        return
      }
      setSelectedFile(file)
      if (!formData.title) {
        setFormData(prev => ({ ...prev, title: file.name.replace(/\.[^/.]+$/, '') }))
      }
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setSuccess('')
    setSubmitting(true)

    try {
      let fileUrl = null
      let fileName = null
      let fileSize = null

      const selectedCompany = companies.find(c => c.id === formData.companyId)
      const companyFolder = selectedCompany 
        ? selectedCompany.company_name.replace(/[^a-zA-Z0-9ğüşıöçĞÜŞİÖÇ\s]/g, '').replace(/\s+/g, '_')
        : formData.companyId

      if (selectedFile) {
        const timestamp = Date.now()
        const safeFileName = selectedFile.name.replace(/[^a-zA-Z0-9ğüşıöçĞÜŞİÖÇ._-]/g, '_')
        const filePath = `${companyFolder}/${timestamp}_${safeFileName}`

        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { error: uploadError } = await (supabase as any).storage
          .from('documents')
          .upload(filePath, selectedFile)

        if (uploadError) {
          console.warn('Storage upload failed:', uploadError)
          setError(`Dosya yüklenemedi: ${uploadError.message}. Belge kaydı dosyasız oluşturulacak.`)
        } else {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const { data: urlData } = (supabase as any).storage
            .from('documents')
            .getPublicUrl(filePath)
          
          fileUrl = urlData?.publicUrl
          fileName = selectedFile.name
          fileSize = selectedFile.size
          setError('')
        }
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { error: insertError } = await (supabase as any)
        .from('documents')
        .insert({
          company_id: formData.companyId,
          document_type: formData.documentType,
          title: formData.title,
          description: formData.description || null,
          file_url: fileUrl,
          file_name: fileName,
          file_size: fileSize,
          status: formData.status,
          valid_from: formData.validFrom || null,
          valid_until: formData.validUntil || null,
        })

      if (insertError) throw insertError

      setSuccess('Belge başarıyla eklendi')
      // Yeni eklenen şirketi aç
      setExpandedCompanies(prev => new Set([...prev, formData.companyId]))
      setTimeout(() => {
        setShowUpload(false)
        setSuccess('')
        setSelectedFile(null)
        setFormData({
          companyId: '', documentType: 'sozlesme', title: '', description: '',
          status: 'signed', validFrom: '', validUntil: ''
        })
        fetchData()
      }, 1500)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Bir hata oluştu')
    } finally {
      setSubmitting(false)
    }
  }

  const deleteDocument = async (id: string) => {
    if (!confirm('Bu belgeyi silmek istediğinize emin misiniz?')) return
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    await (supabase as any).from('documents').delete().eq('id', id)
    fetchData()
  }

  const formatFileSize = (bytes: number | null) => {
    if (!bytes) return '-'
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  }

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleDateString('tr-TR')
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <h1 className="page-title">Belgeler</h1>
        <div className="flex items-center gap-2 sm:gap-3">
          <button onClick={fetchData} disabled={loading}
            className="p-2.5 bg-slate-100 hover:bg-slate-200 text-slate-800 rounded-lg transition-colors disabled:opacity-50">
            <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
          </button>
          <button onClick={() => setShowUpload(true)}
            className="flex items-center gap-2 px-3 sm:px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors text-sm sm:text-base">
            <Upload className="w-5 h-5" /><span className="hidden sm:inline">Belge</span> Ekle
          </button>
        </div>
      </div>

      <div className="flex flex-col gap-4">
        <div className="relative flex-1 sm:max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
          <input type="text" placeholder="Belge veya şirket ara..." value={search} onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-lg text-slate-800 placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500/50" />
        </div>
        <div className="flex items-center gap-2 text-sm text-slate-500">
          <Building2 className="w-4 h-4" />
          <span>{groupedDocuments.length} şirket</span>
          <span className="text-slate-600">•</span>
          <FileText className="w-4 h-4" />
          <span>{documents.length} belge</span>
        </div>
      </div>

      {/* Şirket Listesi - Accordion */}
      <div className="space-y-3">
        {loading ? (
          <div className="flex items-center justify-center py-12 bg-white rounded-xl border border-slate-200">
            <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
          </div>
        ) : groupedDocuments.length === 0 ? (
          <div className="text-center py-12 bg-white rounded-xl border border-slate-200">
            <FileText className="w-12 h-12 text-slate-600 mx-auto mb-3" />
            <p className="text-slate-500">Henüz belge yok</p>
          </div>
        ) : (
          groupedDocuments.map((group) => {
            const isExpanded = expandedCompanies.has(group.company.id)
            const signedCount = group.documents.filter(d => d.status === 'signed').length
            const hasNoDocuments = group.documents.length === 0
            
            return (
              <motion.div
                key={group.company.id}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className={`rounded-xl border overflow-hidden ${
                  hasNoDocuments 
                    ? 'bg-gradient-to-r from-amber-50 to-orange-50 border-amber-200' 
                    : 'bg-white border-slate-200'
                }`}
              >
                {/* Şirket Header */}
                <button
                  onClick={() => hasNoDocuments ? (setFormData(prev => ({ ...prev, companyId: group.company.id })), setShowUpload(true)) : toggleCompany(group.company.id)}
                  className="w-full px-5 py-4 flex items-center justify-between hover:bg-slate-100/50 transition-colors"
                >
                  <div className="flex items-center gap-4">
                    <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                      hasNoDocuments ? 'bg-amber-100' : 'bg-purple-500/20'
                    }`}>
                      <Building2 className={`w-5 h-5 ${hasNoDocuments ? 'text-amber-500' : 'text-purple-400'}`} />
                    </div>
                    <div className="text-left">
                      <h3 className="text-slate-800 font-semibold">{group.company.company_name}</h3>
                      {hasNoDocuments ? (
                        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 bg-amber-100 text-amber-700 rounded text-xs font-medium">
                          <AlertCircle className="w-3 h-3" />
                          Belge Yüklenmemiş
                        </span>
                      ) : (
                        <p className="text-sm text-slate-500">
                          {group.documents.length} belge
                          {signedCount > 0 && (
                            <span className="text-green-400 ml-2">• {signedCount} imzalı</span>
                          )}
                        </p>
                      )}
                    </div>
                  </div>
                  {hasNoDocuments ? (
                    <span className="px-3 py-1.5 bg-amber-500 text-white rounded-lg text-sm font-medium">
                      Belge Ekle
                    </span>
                  ) : (
                    <motion.div
                      animate={{ rotate: isExpanded ? 180 : 0 }}
                      transition={{ duration: 0.2 }}
                    >
                      <ChevronDown className="w-5 h-5 text-slate-500" />
                    </motion.div>
                  )}
                </button>

                {/* Belgeler */}
                <AnimatePresence>
                  {isExpanded && !hasNoDocuments && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: 'auto', opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      transition={{ duration: 0.2 }}
                      className="overflow-hidden"
                    >
                      <div className="border-t border-slate-200">
                        {group.documents.map((doc, index) => {
                          const status = statusLabels[doc.status] || statusLabels.draft
                          return (
                            <div
                              key={doc.id}
                              className={`px-3 sm:px-5 py-3 flex flex-col sm:flex-row sm:items-center justify-between hover:bg-slate-100/30 transition-colors gap-2 sm:gap-0 ${
                                index !== group.documents.length - 1 ? 'border-b border-slate-200/50' : ''
                              }`}
                            >
                              <div className="flex items-center gap-3 flex-1 min-w-0">
                                <div className="w-8 h-8 bg-slate-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                  <FileText className="w-4 h-4 text-blue-400" />
                                </div>
                                <div className="min-w-0 flex-1">
                                  <p className="text-sm text-slate-800 truncate">{doc.title}</p>
                                  <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-xs text-slate-500">
                                    <span className="px-1.5 py-0.5 bg-slate-100 rounded text-slate-500">
                                      {typeLabels[doc.document_type] || doc.document_type}
                                    </span>
                                    <span className="flex items-center gap-1">
                                      <Calendar className="w-3 h-3" />
                                      {formatDate(doc.created_at)}
                                    </span>
                                    {doc.file_size && (
                                      <span className="hidden sm:inline">{formatFileSize(doc.file_size)}</span>
                                    )}
                                  </div>
                                </div>
                              </div>
                              <div className="flex items-center gap-2 ml-11 sm:ml-4">
                                <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                                  status.color === 'green' ? 'bg-green-500/20 text-green-400' :
                                  status.color === 'amber' ? 'bg-amber-500/20 text-amber-400' :
                                  status.color === 'blue' ? 'bg-blue-500/20 text-blue-400' : 'bg-slate-500/20 text-slate-500'
                                }`}>{status.label}</span>
                                {doc.file_url && (
                                  <>
                                    <a href={doc.file_url} target="_blank" rel="noopener noreferrer"
                                      className="p-1.5 text-slate-500 hover:text-slate-800 hover:bg-slate-100 rounded-lg">
                                      <Eye className="w-4 h-4" />
                                    </a>
                                    <a href={doc.file_url} download
                                      className="p-1.5 text-slate-500 hover:text-slate-800 hover:bg-slate-100 rounded-lg">
                                      <Download className="w-4 h-4" />
                                    </a>
                                  </>
                                )}
                                <button onClick={() => deleteDocument(doc.id)}
                                  className="p-1.5 text-red-400 hover:text-red-300 hover:bg-slate-100 rounded-lg">
                                  <Trash2 className="w-4 h-4" />
                                </button>
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            )
          })
        )}
      </div>

      {/* Upload Modal */}
      {showUpload && (
        <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={() => setShowUpload(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-slate-200 max-h-[95vh] sm:max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-slate-200 flex items-center justify-between">
              <h2 className="text-xl font-bold text-slate-800">Belge Ekle</h2>
              <button onClick={() => setShowUpload(false)} className="p-2 text-slate-500 hover:text-slate-800 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              {error && (
                <div className="p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm flex items-center gap-2">
                  <AlertCircle className="w-4 h-4" />{error}
                </div>
              )}
              {success && (
                <div className="p-3 bg-green-500/10 border border-green-500/20 rounded-lg text-green-400 text-sm flex items-center gap-2">
                  <CheckCircle className="w-4 h-4" />{success}
                </div>
              )}

              {companies.length === 0 ? (
                <div className="text-center py-6">
                  <Building2 className="w-10 h-10 text-slate-600 mx-auto mb-2" />
                  <p className="text-slate-500">Önce bir şirket oluşturmalısınız</p>
                </div>
              ) : (
                <>
                  <div>
                    <label className="block text-sm font-medium text-slate-600 mb-2">Dosya</label>
                    <input type="file" ref={fileInputRef} onChange={handleFileSelect} className="hidden"
                      accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png" />
                    <div 
                      onClick={() => fileInputRef.current?.click()}
                      className="border-2 border-dashed border-slate-200 rounded-xl p-6 text-center cursor-pointer hover:border-slate-500 transition-colors"
                    >
                      {selectedFile ? (
                        <div className="flex items-center justify-center gap-3">
                          <FileText className="w-8 h-8 text-blue-400" />
                          <div className="text-left">
                            <p className="text-slate-800 text-sm">{selectedFile.name}</p>
                            <p className="text-slate-500 text-xs">{formatFileSize(selectedFile.size)}</p>
                          </div>
                        </div>
                      ) : (
                        <>
                          <Upload className="w-10 h-10 text-slate-500 mx-auto mb-2" />
                          <p className="text-slate-500 text-sm">Dosya seçmek için tıklayın</p>
                          <p className="text-slate-500 text-xs mt-1">PDF, DOC, XLS, JPG (max 10MB)</p>
                        </>
                      )}
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-600 mb-1">Şirket *</label>
                    <CustomSelect
                      name="companyId"
                      value={formData.companyId}
                      onChange={(e) => setFormData(prev => ({ ...prev, companyId: e.target.value }))}
                      placeholder="Şirket seçin"
                      required
                      variant="admin"
                      options={companies.map(c => ({ value: c.id, label: c.company_name }))}
                    />
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-600 mb-1">Belge Türü *</label>
                      <CustomSelect
                        name="documentType"
                        value={formData.documentType}
                        onChange={(e) => setFormData(prev => ({ ...prev, documentType: e.target.value }))}
                        placeholder="Belge türü seçin"
                        required
                        variant="admin"
                        options={Object.entries(typeLabels).map(([value, label]) => ({ value, label }))}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-600 mb-1">Durum</label>
                      <CustomSelect
                        name="status"
                        value={formData.status}
                        onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                        placeholder="Durum seçin"
                        variant="admin"
                        options={Object.entries(statusLabels).map(([value, { label }]) => ({ value, label }))}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-600 mb-1">Belge Başlığı *</label>
                    <input type="text" required value={formData.title}
                      onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                      className="w-full px-4 py-2.5 bg-slate-100 border border-slate-200 rounded-lg text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/50"
                      placeholder="Örn: 2026 Yılı Hizmet Sözleşmesi" />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-600 mb-1">Açıklama</label>
                    <textarea value={formData.description} rows={2}
                      onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                      className="w-full px-4 py-2.5 bg-slate-100 border border-slate-200 rounded-lg text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/50 resize-none" />
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-600 mb-1">Geçerlilik Başlangıç</label>
                      <input type="date" value={formData.validFrom}
                        onChange={(e) => setFormData(prev => ({ ...prev, validFrom: e.target.value }))}
                        className="w-full px-4 py-2.5 bg-slate-100 border border-slate-200 rounded-lg text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/50" />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-600 mb-1">Geçerlilik Bitiş</label>
                      <input type="date" value={formData.validUntil}
                        onChange={(e) => setFormData(prev => ({ ...prev, validUntil: e.target.value }))}
                        className="w-full px-4 py-2.5 bg-slate-100 border border-slate-200 rounded-lg text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/50" />
                    </div>
                  </div>

                  <div className="flex gap-3 pt-4">
                    <button type="button" onClick={() => setShowUpload(false)}
                      className="flex-1 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-800 rounded-lg font-medium transition-colors">
                      İptal
                    </button>
                    <button type="submit" disabled={submitting}
                      className="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-slate-800 rounded-lg font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-2">
                      {submitting ? <><Loader2 className="w-4 h-4 animate-spin" />Yükleniyor...</> : 'Belge Ekle'}
                    </button>
                  </div>
                </>
              )}
            </form>
          </motion.div>
        </motion.div>
      )}
    </div>
  )
}
