"use client"

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { FileText, Download, Eye, Loader2, Search } from 'lucide-react'
import { useAuth } from '@/lib/auth/AuthProvider'
import { getSupabaseClient } from '@/lib/supabase/client'

interface Document {
  id: string
  title: string
  description: string | null
  document_type: string
  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
}

const typeLabels: Record<string, string> = {
  teklif: 'Teklif Belgesi',
  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'
}

export default function PortalBelgelerPage() {
  const { user } = useAuth()
  const [documents, setDocuments] = useState<Document[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')

  useEffect(() => {
    const fetchDocuments = async () => {
      if (!user) return
      
      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('documents')
          .select('*')
          .eq('company_id', company.id)
          .order('created_at', { ascending: false })

        if (data) setDocuments(data)
      }
      
      setLoading(false)
    }

    fetchDocuments()
  }, [user])

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleDateString('tr-TR')
  }

  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 filtered = documents.filter(d => 
    d.title.toLowerCase().includes(search.toLowerCase())
  )

  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">
      <h1 className="text-lg sm:text-xl font-semibold text-gray-800">Belgelerim</h1>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 sm:w-5 sm:h-5 text-gray-400" />
        <input type="text" placeholder="Belge ara..." value={search} onChange={(e) => setSearch(e.target.value)}
          className="w-full pl-9 sm:pl-10 pr-4 py-2 sm:py-2.5 bg-white border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500" />
      </div>

      {filtered.length === 0 ? (
        <div className="bg-white rounded-xl border border-gray-100 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">
            {documents.length === 0 ? 'Henüz belge bulunmuyor' : 'Arama sonucu bulunamadı'}
          </p>
        </div>
      ) : (
        <>
          {/* Mobile Card View */}
          <div className="md:hidden space-y-3">
            {filtered.map((doc, index) => (
              <motion.div
                key={doc.id}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: index * 0.05 }}
                className="bg-white rounded-xl border border-gray-100 p-3"
              >
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0">
                    <FileText className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">{doc.title}</p>
                    <div className="flex flex-wrap items-center gap-2 mt-1">
                      <span className="px-1.5 py-0.5 text-[10px] font-medium rounded bg-gray-100 text-gray-600">
                        {typeLabels[doc.document_type] || doc.document_type}
                      </span>
                      <span className="text-[10px] text-gray-400">{formatDate(doc.created_at)}</span>
                      {doc.file_size && <span className="text-[10px] text-gray-400">{formatFileSize(doc.file_size)}</span>}
                    </div>
                  </div>
                </div>
                {doc.file_url && (
                  <div className="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100">
                    <a href={doc.file_url} target="_blank" rel="noopener noreferrer"
                      className="flex-1 py-2 px-3 text-xs font-medium text-center bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors flex items-center justify-center gap-1.5">
                      <Eye className="w-3.5 h-3.5" /> Görüntüle
                    </a>
                    <a href={doc.file_url} download
                      className="flex-1 py-2 px-3 text-xs font-medium text-center bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors flex items-center justify-center gap-1.5">
                      <Download className="w-3.5 h-3.5" /> İndir
                    </a>
                  </div>
                )}
              </motion.div>
            ))}
          </div>

          {/* Desktop Table View */}
          <div className="hidden md:block bg-white rounded-xl border border-gray-100 overflow-hidden">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Belge</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tür</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tarih</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Boyut</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">İşlem</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {filtered.map((doc, index) => (
                  <motion.tr
                    key={doc.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: index * 0.05 }}
                    className="hover:bg-gray-50 transition-colors"
                  >
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                          <FileText className="w-5 h-5 text-blue-600" />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-900">{doc.title}</p>
                          {doc.description && (
                            <p className="text-xs text-gray-500 truncate max-w-xs">{doc.description}</p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-4">
                      <span className="px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-600">
                        {typeLabels[doc.document_type] || doc.document_type}
                      </span>
                    </td>
                    <td className="px-4 py-4 text-sm text-gray-500">{formatDate(doc.created_at)}</td>
                    <td className="px-4 py-4 text-sm text-gray-500">{formatFileSize(doc.file_size)}</td>
                    <td className="px-4 py-4 text-right">
                      {doc.file_url ? (
                        <div className="flex items-center justify-end gap-2">
                          <a href={doc.file_url} target="_blank" rel="noopener noreferrer"
                            className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
                            <Eye className="w-4 h-4" />
                          </a>
                          <a href={doc.file_url} download
                            className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
                            <Download className="w-4 h-4" />
                          </a>
                        </div>
                      ) : (
                        <span className="text-xs text-gray-400">Dosya yok</span>
                      )}
                    </td>
                  </motion.tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  )
}
