'use client'

import { useState } from 'react'
import { invitePartner, acceptInvite } from '@/actions/couple'

export interface CoupleStatusData {
  linked?: boolean;
  pendingInvites?: { id: string; remetente_id: string }[];
}

export default function CoupleManager({ initialStatus }: { initialStatus: CoupleStatusData }) {
  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)
  const [inviteSent, setInviteSent] = useState(false)
  
  const handleInvite = async (e: React.FormEvent) => {
    e.preventDefault()
    if(!email) return
    setLoading(true)
    const formData = new FormData()
    formData.append('partnerEmail', email)
    
    const res = await invitePartner(formData)
    setLoading(false)
    if(res.success) {
      setInviteSent(true)
      setEmail('')
    } else {
      alert("Erro ao enviar convite: " + res.error)
    }
  }

  const handleAccept = async (inviteId: string) => {
    setLoading(true)
    const res = await acceptInvite(inviteId)
    setLoading(false)
    if(!res.success) {
      alert("Erro ao aceitar convite: " + res.error)
    }
  }

  return (
    <div className="space-y-4">
      {initialStatus?.linked ? (
        <div className="flex items-center gap-4 p-4 bg-surface-container-high rounded-2xl border border-[#c3f400]/50 transition-colors">
          <div className="w-12 h-12 rounded-full bg-[#c3f400]/20 flex items-center justify-center">
            <span className="material-symbols-outlined text-[#c3f400] font-bold">favorite</span>
          </div>
          <div className="flex-1">
            <p className="font-bold text-sm text-white font-headline">Parceiro Conectado</p>
            <p className="text-xs text-white/50">Sincronização ativa</p>
          </div>
          <button className="material-symbols-outlined text-white/50 hover:text-[#ffb4a4] transition-colors p-2">settings</button>
        </div>
      ) : (
        <div className="space-y-4">
          {(initialStatus?.pendingInvites?.length ?? 0) > 0 && (
            <div className="bg-surface-container-high p-4 rounded-2xl border border-[#c3f400]/20">
              <h5 className="font-bold text-sm text-white mb-3">Convites Pendentes</h5>
              {initialStatus?.pendingInvites?.map((invite) => (
                <div key={invite.id} className="flex justify-between items-center bg-surface-container-low p-3 rounded-xl">
                  <span className="text-xs text-white/70">De: {invite.remetente_id}</span>
                  <button 
                    onClick={() => handleAccept(invite.id)}
                    disabled={loading}
                    className="px-3 py-1 bg-[#c3f400] text-on-primary-fixed text-xs font-bold rounded-lg"
                  >
                    Aceitar
                  </button>
                </div>
              ))}
            </div>
          )}

          {!inviteSent ? (
            <form onSubmit={handleInvite} className="flex flex-col gap-3">
              <p className="text-xs text-white/50 font-medium">Conecte-se com seu parceiro pelo e-mail:</p>
              <div className="flex gap-2">
                <input 
                  type="email" 
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  placeholder="email@parceiro.com" 
                  className="flex-1 bg-surface-container-high border border-white/10 rounded-xl px-4 text-sm text-white focus:outline-none focus:border-[#c3f400]"
                  required
                />
                <button 
                  type="submit"
                  disabled={loading}
                  className="bg-[#c3f400] text-on-primary-fixed px-4 py-2 rounded-xl font-bold text-sm flex items-center gap-2 hover:bg-[#b0dc00] disabled:opacity-50"
                >
                  {loading ? '...' : (
                    <>
                      <span className="material-symbols-outlined text-sm">send</span>
                      Convidar
                    </>
                  )}
                </button>
              </div>
            </form>
          ) : (
            <div className="p-4 bg-[#c3f400]/10 border border-[#c3f400]/30 rounded-2xl text-center">
              <p className="text-sm font-bold text-[#c3f400]">Convite enviado com sucesso!</p>
              <p className="text-xs text-white/50 mt-1">Aguardando seu parceiro aceitar.</p>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
