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 { useNavigate } from 'react-router-dom'

interface Props {
  onClose: () => void
}

export function DeleteAccountModal({ onClose }: Props) {
  const logout = useAuthStore((s) => s.logout)
  const navigate = useNavigate()
  const [password, setPassword] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleDelete = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!password) return

    setIsSubmitting(true)
    setError(null)
    try {
      await accountsApi.deleteAccount(password)
      await logout()
      navigate('/login')
    } catch (err) {
      const axiosErr = err as { response?: { data?: { detail?: string } } }
      setError(axiosErr.response?.data?.detail ?? 'Failed to delete account')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="card-flat w-full max-w-md p-6">
        <div className="flex items-center gap-2 text-rose-500 mb-4">
          <AlertTriangle className="h-5 w-5" />
          <h2 className="text-lg font-semibold font-heading text-foreground">Delete Account</h2>
        </div>
        <p className="text-sm text-muted-foreground mb-4">
          This action is <strong className="text-rose-400">permanent</strong>. Your account, data,
          and all associated flows will be permanently deleted.
        </p>

        <form onSubmit={handleDelete} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-foreground">Confirm Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              className={cn(
                'mt-1 block w-full rounded-lg border border-border bg-card px-3 py-2',
                'text-foreground focus:border-primary focus:outline-hidden'
              )}
            />
          </div>

          {error && <p className="text-sm text-rose-500">{error}</p>}

          <div className="flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className={cn(
                'rounded-lg px-4 py-2 text-sm font-medium',
                'bg-input border border-border text-foreground'
              )}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting || !password}
              className={cn(
                'rounded-lg 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" /> : 'Delete Forever'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
