'use client'

import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { gql } from 'graphql-tag'
import { apolloClient } from '@/lib/graphql/client'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'

const LOGIN_MUTATION = gql`
  mutation Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      token
      user {
        id
        email
        name
        role
      }
    }
  }
`

export function LoginForm() {
  const router = useRouter()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  const loginMutation = useMutation({
    mutationFn: async (variables: { email: string; password: string }) => {
      const result = await apolloClient.mutate({
        mutation: LOGIN_MUTATION,
        variables,
      })
      return result.data.login
    },
    onSuccess: async (data) => {
      // Store token in httpOnly cookie
      const { setAuthToken } = await import('@/lib/auth-storage')
      await setAuthToken(data.token)
      router.push('/dashboard')
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    loginMutation.mutate({ email, password })
  }

  return (
    <Card className="w-full max-w-md mx-auto border-studio-medium bg-studio-dark">
      <CardHeader>
        <CardTitle className="text-2xl text-white text-center">
          Sign In to Sankofa Phoenix
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              placeholder="admin@sankofa.nexus"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          {loginMutation.isError && (
            <div className="text-red-400 text-sm">
              {(loginMutation.error as Error).message || 'Login failed'}
            </div>
          )}
          <Button
            type="submit"
            variant="phoenix"
            className="w-full"
            disabled={loginMutation.isPending}
          >
            {loginMutation.isPending ? 'Signing in...' : 'Sign In'}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}

