import { useState } from 'react'
import { Loader2, AlertTriangle } from 'lucide-react'
import { accountsApi } from '@/api/accounts'
import { useAuthStore } from '@/store/authStore'
import { cn } from '@/lib/utils'
import { toast } from '@/lib/toast'

interface Props {
  accountName: string
  onClose: () => void
}

export function LeaveAccountModal({ accountName, onClose }: Props) {
  const fetchUser = useAuthStore((s) => s.fetchUser)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleLeave = async () => {
    setIsSubmitting(true)
    try {
      await accountsApi.leaveAccount()
      toast.success('You have left the account')
      await fetchUser()
      onClose()
    } catch (err) {
      const axiosErr = err as { response?: { data?: { detail?: string } } }
      toast.error(axiosErr.response?.data?.detail ?? 'Failed to leave account')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="glass-card-static w-full max-w-md p-6">
        <div className="flex items-center gap-2 text-amber-400 mb-4">
          <AlertTriangle className="h-5 w-5" />
          <h2 className="text-lg font-semibold font-heading text-foreground">Leave Account</h2>
        </div>
        <p className="text-sm text-muted-foreground mb-4">
          Are you sure you want to leave <strong className="text-foreground">{accountName}</strong>?
          A new personal account will be created for you.
        </p>
        <div className="flex justify-end gap-3">
          <button
            onClick={onClose}
            className={cn(
              'rounded-[10px] px-4 py-2 text-sm font-medium',
              'bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-foreground'
            )}
          >
            Cancel
          </button>
          <button
            onClick={handleLeave}
            disabled={isSubmitting}
            className={cn(
              'rounded-[10px] px-4 py-2 text-sm font-semibold',
              'bg-rose-500 text-white hover:bg-rose-400 disabled:opacity-50'
            )}
          >
            {isSubmitting ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Leave Account'}
          </button>
        </div>
      </div>
    </div>
  )
}
