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

interface Props {
  members: AccountMember[]
  onClose: () => void
  onTransferred: () => void
}

export function TransferOwnershipModal({ members, onClose, onTransferred }: Props) {
  const user = useAuthStore((s) => s.user)
  const nonOwnerMembers = members.filter((m) => m.id !== user?.id)
  const [targetUserId, setTargetUserId] = useState(nonOwnerMembers[0]?.id ?? '')
  const [password, setPassword] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

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

    setIsSubmitting(true)
    setError(null)
    try {
      await accountsApi.transferOwnership(password, targetUserId)
      toast.success('Ownership transferred')
      onTransferred()
    } catch (err) {
      const axiosErr = err as { response?: { data?: { detail?: string } } }
      setError(axiosErr.response?.data?.detail ?? 'Transfer failed')
    } 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-amber-400 mb-4">
          <AlertTriangle className="h-5 w-5" />
          <h2 className="text-lg font-semibold font-heading text-foreground">Transfer Ownership</h2>
        </div>
        <p className="text-sm text-muted-foreground mb-4">
          This will make the selected member the new account owner. You will become an engineer.
        </p>

        {nonOwnerMembers.length === 0 ? (
          <p className="text-sm text-muted-foreground">No other members to transfer to.</p>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-foreground">New Owner</label>
              <select
                value={targetUserId}
                onChange={(e) => setTargetUserId(e.target.value)}
                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'
                )}
              >
                {nonOwnerMembers.map((m) => (
                  <option key={m.id} value={m.id}>{m.name} ({m.email})</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground">Your 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-amber-500 text-white hover:bg-amber-400',
                  'disabled:opacity-50'
                )}
              >
                {isSubmitting ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Transfer'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  )
}
