'use client'

import { useRef } from 'react'
import { Download, FileText, Loader2, Trash2, Upload } from 'lucide-react'
import Loading from '@/components/ui/Loader/Loading'
import { ClientData } from '@/types'
import { fmtBytes, fmtDate } from '@/utils'
import { useDocuments } from '@/hooks/client/useDocuments'

const API_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000'



const DOC_LABELS: Record<string, string> = {
  CIN: 'CIN Document',
  PAN: 'PAN Document',
  LEI: 'LEI Document',
  MOA_AOA: 'MOA & AOA / Partnership Deed',
}

export default function DocumentsSection({ client }: { client: ClientData }) {
  const { docs, loading, uploading, handleUpload, handleDelete, uniqueDocTypes } = useDocuments(client)
  const fileRefs = useRef<Record<string, HTMLInputElement | null>>({})

  if (loading) return <Loading name='' />
  return (
    <div className="space-y-2">
      {uniqueDocTypes.map(docType => {
        const label = DOC_LABELS[docType] ?? (docType.startsWith('GST_') ? `GST Certificate — ${docType.replace('GST_', '')}` : docType)
        const uploaded = docs.filter(d => d.docType === docType)
        const isUp = uploading === docType

        return (
          <div key={docType} className="border border-gray-200 rounded-xl bg-white overflow-hidden">

            <div className="flex items-center justify-between px-4 py-2.5">
              <div className="flex items-center gap-2">
                <FileText className="w-4 h-4 text-gray-400 flex-shrink-0" />
                <span className="text-sm font-medium text-gray-800">{label}</span>
                {uploaded.length > 0
                  ? <span className="text-[9px] font-bold text-green-700 bg-green-50 border border-green-200 px-1.5 py-0.5 rounded uppercase tracking-widest">Uploaded</span>
                  : <span className="text-[9px] font-bold text-amber-700 bg-amber-50 border border-amber-200 px-1.5 py-0.5 rounded uppercase tracking-widest">Pending</span>
                }
              </div>
              <button
                onClick={() => fileRefs.current[docType]?.click()}
                disabled={isUp}
                className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-gray-600 disabled:opacity-50"
              >
                {isUp ? <Loader2 className="w-3 h-3 animate-spin" /> : <Upload className="w-3 h-3" />}
                {isUp ? 'Uploading…' : 'Upload PDF'}
              </button>
              <input
                ref={el => { fileRefs.current[docType] = el }}
                type="file" accept="application/pdf" className="hidden"
                onChange={e => {
                  const f = e.target.files?.[0]
                  if (f) handleUpload(docType, f)
                  e.target.value = ''
                }}
              />
            </div>

            {uploaded.length > 0 && (
              <div className="border-t border-gray-100 bg-gray-50 px-4 py-2 space-y-1.5">
                {uploaded.map(doc => (
                  <div key={doc.id} className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-2 min-w-0">
                      <FileText className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
                      <span className="text-xs text-gray-700 truncate">{doc.fileName}</span>
                      {doc.fileSize && <span className="text-[10px] text-gray-400 flex-shrink-0">{fmtBytes(doc.fileSize)}</span>}
                      <span className="text-[10px] text-gray-400 flex-shrink-0">{fmtDate(doc.uploadedAt)}</span>
                    </div>
                    <div className="flex items-center gap-1 flex-shrink-0">
                      <a
                        href={`${API_URL}${doc.filePath}`}
                        target="_blank" rel="noopener noreferrer" download
                        className="p-1.5 rounded-lg text-gray-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                        title="Download"
                      >
                        <Download className="w-3.5 h-3.5" />
                      </a>
                      <button
                        onClick={() => handleDelete(doc.id)}
                        className="p-1.5 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )
      })}
    </div>
  )
}
