'use client'

import { useState, useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Header } from '@/components/layout/header'
import { Key, ArrowRight, Loader2 } from 'lucide-react'
import { initiateSSO, getPortalForRole, isAuthenticated } from '@/lib/auth/sso'

export default function SignInPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [ssoLoading, setSsoLoading] = useState(false)

  // Check if already authenticated
  useEffect(() => {
    if (isAuthenticated()) {
      router.push('/portal')
    }
  }, [router])

  // Handle Keycloak SSO callback
  useEffect(() => {
    const code = searchParams?.get('code')
    const state = searchParams?.get('state')
    
    if (code && state) {
      // Handle SSO callback - would integrate with actual Keycloak
      // For now, redirect to portal
      router.push('/portal')
    }
  }, [searchParams, router])

  const handleSignIn = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')

    try {
      // TODO: Integrate with actual authentication API
      // For now, use GraphQL login mutation
      const response = await fetch(
        process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            query: `
              mutation Login($email: String!, $password: String!) {
                login(email: $email, password: $password) {
                  token
                  user {
                    id
                    email
                    name
                    role
                  }
                }
              }
            `,
            variables: { email, password },
          }),
        }
      )

      const result = await response.json()

      if (result.errors) {
        setError(result.errors[0].message || 'Invalid email or password')
        setLoading(false)
        return
      }

      if (result.data?.login) {
        // Store token
        if (typeof window !== 'undefined') {
          sessionStorage.setItem('auth_token', result.data.login.token)
          localStorage.setItem('phoenix_token', result.data.login.token)
        }

        // Determine portal based on role
        const role = result.data.login.user.role.toLowerCase()
        const portal = getPortalForRole(role)
        router.push(portal)
      }
    } catch (err) {
      setError('Failed to sign in. Please try again.')
      console.error('Sign in error:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleKeycloakSSO = async () => {
    setSsoLoading(true)
    try {
      const keycloakUrl = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://keycloak.sankofa.nexus'
      const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'sankofa'
      const clientId = process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'phoenix-portal'
      const redirectUri = `${window.location.origin}/portal/signin`

      const ssoUrl = await initiateSSO({
        keycloakUrl,
        realm,
        clientId,
        redirectUri,
      })

      window.location.href = ssoUrl
    } catch (err) {
      setError('Failed to initiate SSO. Please try again.')
      console.error('SSO error:', err)
      setSsoLoading(false)
    }
  }

  const isKeycloakConfigured =
    typeof window !== 'undefined' &&
    (process.env.NEXT_PUBLIC_KEYCLOAK_URL || process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID)

  return (
    <>
      <Header />
      <main className="min-h-screen bg-studio-black flex items-center justify-center px-4">
        <Card className="w-full max-w-md border-studio-medium">
          <CardHeader className="text-center">
            <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-phoenix-fire/20">
              <Key className="h-6 w-6 text-phoenix-fire" />
            </div>
            <CardTitle className="text-2xl">Sign In</CardTitle>
            <CardDescription>
              Access your Phoenix Nexus portals
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSignIn} className="space-y-4">
              {error && (
                <div className="rounded bg-red-500/10 px-4 py-3 text-sm text-red-500">
                  {error}
                </div>
              )}

              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  disabled={loading}
                />
              </div>

              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label htmlFor="password">Password</Label>
                  <Link
                    href="/portal/forgot-password"
                    className="text-sm text-phoenix-fire hover:underline"
                  >
                    Forgot password?
                  </Link>
                </div>
                <Input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  disabled={loading}
                />
              </div>

              <Button
                type="submit"
                variant="phoenix"
                className="w-full"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Signing in...
                  </>
                ) : (
                  <>
                    Sign In
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </>
                )}
              </Button>

              <div className="text-center text-sm text-gray-400">
                Don't have an account?{' '}
                <Link href="/portal/get-started" className="text-phoenix-fire hover:underline">
                  Get started
                </Link>
              </div>
            </form>

            {isKeycloakConfigured && (
              <div className="mt-6 border-t border-studio-medium pt-6">
                <p className="mb-4 text-center text-sm text-gray-400">
                  Or continue with
                </p>
                <div className="space-y-2">
                  <Button
                    variant="outline"
                    className="w-full"
                    onClick={handleKeycloakSSO}
                    disabled={ssoLoading || loading}
                  >
                    {ssoLoading ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Connecting...
                      </>
                    ) : (
                      'Keycloak SSO'
                    )}
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </>
  )
}
