import { useState, useEffect } from 'react'
import { Shell } from '@/layouts/Shell'
import { useAuth } from '@/context/AuthContext'
import { adminService } from '@/services/adminService'
import { financialService, CompanyDocument } from '@/services/financialService'
import { Company } from '@/services/adminService'

export function MyProfilePage() {
  const { user, login } = useAuth()
  const [isEditing, setIsEditing] = useState(false)
  const [loading, setLoading] = useState(false)
  const [formData, setFormData] = useState({
    name: user?.name || '',
    email: user?.email || '',
    username: user?.username || ''
  })

  const [company, setCompany] = useState<Company | null>(null)
  const [documents, setDocuments] = useState<CompanyDocument[]>([])
  const [uploading, setUploading] = useState(false)

  useEffect(() => {
    loadCompanyData()
  }, [])

  const loadCompanyData = async () => {
    try {
      const c = await financialService.getMyCompany()
      setCompany(c)
      const d = await financialService.listDocuments()
      setDocuments(d || [])
    } catch (err) {
      console.error('Failed to load company data', err)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value })
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!user) return
    setLoading(true)
    try {
      const updatedUser = await adminService.updateUser(user.id, {
        name: formData.name,
        email: formData.email,
        username: formData.username
      })

      login(
        user.token,
        user.role,
        updatedUser.name,
        updatedUser.id,
        updatedUser.company_id,
        updatedUser.email,
        updatedUser.username
      )

      setIsEditing(false)
      alert('Perfil atualizado com sucesso!')
    } catch (err) {
      console.error('Error updating profile', err)
      alert('Erro ao atualizar perfil. Tente novamente.')
    } finally {
      setLoading(false)
    }
  }

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.length) return
    const file = e.target.files[0]
    setUploading(true)
    try {
      await financialService.uploadDocument(file, 'license') // Defaulting to license for now, could be select
      await loadCompanyData()
      alert('Documento enviado com sucesso!')
    } catch (err) {
      console.error('Upload failed', err)
      alert('Erro ao enviar documento.')
    } finally {
      setUploading(false)
    }
  }

  return (
    <Shell>
      <div className="space-y-8 max-w-5xl mx-auto">

        {/* User Profile Section */}
        <div className="rounded-lg bg-white p-6 shadow-sm border border-gray-100">
          <div className="flex justify-between items-center mb-6">
            <div>
              <h1 className="text-xl font-semibold text-medicalBlue">Meus Dados</h1>
              <p className="text-sm text-gray-600">Informações da sua conta de acesso.</p>
            </div>
            {!isEditing ? (
              <button
                onClick={() => setIsEditing(true)}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 transition-colors shadow-sm"
              >
                Editar Dados
              </button>
            ) : (
              <button
                onClick={() => {
                  setIsEditing(false)
                  setFormData({
                    name: user?.name || '',
                    email: user?.email || '',
                    username: user?.username || ''
                  })
                }}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors"
              >
                Cancelar
              </button>
            )}
          </div>

          <form onSubmit={handleSave} className="grid gap-6">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="rounded-md border border-gray-200 p-4 relative bg-gray-50/50">
                <label className="text-xs uppercase text-gray-400 block mb-1 tracking-wider">Nome</label>
                {isEditing ? (
                  <input
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    className="w-full p-1 border-b border-blue-500 focus:outline-none text-sm font-medium text-gray-800 bg-transparent"
                  />
                ) : (
                  <p className="text-sm font-medium text-gray-900">{user?.name ?? 'Não informado'}</p>
                )}
              </div>

              <div className="rounded-md border border-gray-200 p-4 bg-gray-50">
                <p className="text-xs uppercase text-gray-400 mb-1 tracking-wider">Função</p>
                <p className="text-sm font-medium text-gray-900 capitalize">{user?.role ?? 'Não informado'}</p>
                {isEditing && <span className="text-[10px] text-gray-500 absolute top-2 right-2">(Leitura)</span>}
              </div>

              <div className="rounded-md border border-gray-200 p-4 relative bg-gray-50/50">
                <label className="text-xs uppercase text-gray-400 block mb-1 tracking-wider">E-mail</label>
                {isEditing ? (
                  <input
                    name="email"
                    type="email"
                    value={formData.email}
                    onChange={handleChange}
                    className="w-full p-1 border-b border-blue-500 focus:outline-none text-sm font-medium text-gray-800 bg-transparent"
                  />
                ) : (
                  <p className="text-sm font-medium text-gray-900">{user?.email ?? 'Não informado'}</p>
                )}
              </div>

              <div className="rounded-md border border-gray-200 p-4 relative bg-gray-50/50">
                <label className="text-xs uppercase text-gray-400 block mb-1 tracking-wider">Usuário</label>
                {isEditing ? (
                  <input
                    name="username"
                    value={formData.username}
                    onChange={handleChange}
                    className="w-full p-1 border-b border-blue-500 focus:outline-none text-sm font-medium text-gray-800 bg-transparent"
                  />
                ) : (
                  <p className="text-sm font-medium text-gray-900">{user?.username ?? 'Não informado'}</p>
                )}
              </div>
            </div>

            {isEditing && (
              <div className="flex justify-end pt-4 border-t border-gray-100">
                <button
                  type="submit"
                  disabled={loading}
                  className="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg font-medium shadow-sm disabled:opacity-50 transition-all flex items-center gap-2"
                >
                  {loading ? 'Salvando...' : 'Salvar Alterações'}
                </button>
              </div>
            )}
          </form>
        </div>

        {/* Company Profile Section */}
        {company && (
          <div className="rounded-lg bg-white p-6 shadow-sm border border-gray-100">
            <div className="mb-6 flex items-center justify-between">
              <div>
                <h2 className="text-xl font-semibold text-medicalBlue">Dados da Empresa</h2>
                <p className="text-sm text-gray-600">Informações jurídicas e endereço.</p>
              </div>
              <span className={`px-3 py-1 rounded-full text-xs font-semibold ${company.is_verified ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}`}>
                {company.is_verified ? 'Verificada' : 'Pendente de Verificação'}
              </span>
            </div>

            <div className="grid gap-4 sm:grid-cols-2 mb-6">
              <div className="p-4 border border-gray-100 rounded bg-gray-50">
                <label className="text-xs text-gray-500 uppercase">Razão Social</label>
                <div className="font-medium text-gray-900">{company.corporate_name}</div>
              </div>
              <div className="p-4 border border-gray-100 rounded bg-gray-50">
                <label className="text-xs text-gray-500 uppercase">CNPJ</label>
                <div className="font-medium text-gray-900">{company.cnpj}</div>
              </div>
              <div className="p-4 border border-gray-100 rounded bg-gray-50">
                <label className="text-xs text-gray-500 uppercase">Licença / CRF</label>
                <div className="font-medium text-gray-900">{company.license_number}</div>
              </div>
              <div className="p-4 border border-gray-100 rounded bg-gray-50">
                <label className="text-xs text-gray-500 uppercase">Localização</label>
                <div className="font-medium text-gray-900">{company.city} - {company.state}</div>
              </div>
            </div>

            {/* Documents Section */}
            <div className="border-t pt-6">
              <h3 className="text-lg font-medium text-gray-800 mb-4">Documentos da Empresa (KYC)</h3>

              <div className="bg-blue-50 border border-blue-100 rounded p-4 mb-4 flex gap-4 items-start">
                <div className="text-blue-600 mt-1">
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                </div>
                <div className="text-sm text-blue-800">
                  <p className="font-semibold">Envie seus documentos para verificação.</p>
                  <p>Necessário enviar documentos válidos (Licença Sanitária, CRF, Contrato Social) para desbloquear vendas no marketplace.</p>
                </div>
              </div>

              <div className="mb-4">
                <label className="inline-block bg-white border border-gray-300 text-gray-700 font-medium py-2 px-4 rounded cursor-pointer hover:bg-gray-50 transition-colors shadow-sm">
                  {uploading ? 'Enviando...' : '📤 Enviar Novo Documento'}
                  <input type="file" className="hidden" onChange={handleUpload} disabled={uploading} accept=".pdf,.jpg,.png,.jpeg" />
                </label>
              </div>

              {documents.length === 0 ? (
                <p className="text-gray-500 text-sm italic">Nenhum documento enviado.</p>
              ) : (
                <div className="overflow-hidden border rounded-lg shadow-sm">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tipo</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Data</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Ações</th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {documents.map((doc) => (
                        <tr key={doc.id}>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{doc.type || 'Documento'}</td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                              ${doc.status === 'APPROVED' ? 'bg-green-100 text-green-800' :
                                doc.status === 'REJECTED' ? 'bg-red-100 text-red-800' :
                                  'bg-yellow-100 text-yellow-800'}`}>
                              {doc.status}
                            </span>
                            {doc.rejection_reason && (
                              <p className="text-xs text-red-600 mt-1">{doc.rejection_reason}</p>
                            )}
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {new Date(doc.created_at).toLocaleDateString()}
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-blue-600 hover:text-blue-900">
                            <a href={doc.url} target="_blank" rel="noopener noreferrer">Ver Documento</a>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </Shell>
  )
}
