import React, { useState } from 'react'
import { cn } from '../../utils/cn'
import { useLicenseCheck } from '../../hooks/use-license-check'
import { LicenseError } from '../../components/license-error'
import { Skeleton } from '../../components/ui/skeleton'
import type { LoginFormProps, LoginData } from './types'

export function LoginFormCore({
  theme = {},
  className,
  layout = 'single',
  logo,
  header,
  footer,
  features = {},
  onSubmit,
  onSocialLogin,
  onForgotPassword,
  validation,
  texts = {},
  autoFocus = true,
  disabled = false,
}: LoginFormProps) {
  const { isValid, isLoading } = useLicenseCheck()
  const [formData, setFormData] = useState<LoginData>({
    email: '',
    password: '',
    rememberMe: false,
  })
  const [errors, setErrors] = useState<Partial<LoginData>>({})
  const [isSubmitting, setIsSubmitting] = useState(false)

  // License kontrolü
  if (isLoading) {
    return <Skeleton className="w-full h-96" />
  }

  if (!isValid) {
    return <LicenseError className={className} />
  }

  // Form submit handler
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (disabled || isSubmitting) return

    // Validation
    const newErrors: Partial<LoginData> = {}
    
    if (validation?.email) {
      const emailError = validation.email(formData.email)
      if (emailError) newErrors.email = emailError
    } else if (!formData.email) {
      newErrors.email = 'Email is required'
    }

    if (validation?.password) {
      const passwordError = validation.password(formData.password)
      if (passwordError) newErrors.password = passwordError
    } else if (!formData.password) {
      newErrors.password = 'Password is required'
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors)
      return
    }

    setIsSubmitting(true)
    try {
      await onSubmit?.(formData)
    } catch (error) {
      console.error('Login error:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  // Social login handler
  const handleSocialLogin = async (provider: string) => {
    if (disabled || isSubmitting) return
    
    setIsSubmitting(true)
    try {
      await onSocialLogin?.(provider)
    } catch (error) {
      console.error('Social login error:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  // Layout classes
  const layoutClasses = {
    single: 'max-w-md mx-auto',
    'two-column': 'grid md:grid-cols-2 gap-8',
    centered: 'max-w-md mx-auto text-center',
  }

  // Theme styles
  const themeStyles = {
    '--login-primary': theme.primary || '#6366f1',
    '--login-secondary': theme.secondary || '#8b5cf6',
    '--login-background': theme.background || '#ffffff',
    '--login-text': theme.text || '#1f2937',
    '--login-border-radius': theme.borderRadius || '0.5rem',
    '--login-spacing': theme.spacing === 'compact' ? '0.5rem' : theme.spacing === 'relaxed' ? '1.5rem' : '1rem',
  } as React.CSSProperties

  return (
    <div
      className={cn(
        'w-full',
        layoutClasses[layout],
        className
      )}
      style={themeStyles}
    >
      <div className="space-y-6 p-8 rounded-lg border bg-[var(--login-background)] shadow-sm">
        {/* Logo & Header */}
        {(logo || header) && (
          <div className="space-y-4">
            {logo && <div className="flex justify-center">{logo}</div>}
            {header}
          </div>
        )}

        {/* Title */}
        <div className="space-y-2 text-center">
          <h2 className="text-2xl font-bold text-[var(--login-text)]">
            {texts.title || 'Welcome back'}
          </h2>
          {texts.subtitle && (
            <p className="text-sm text-gray-600">{texts.subtitle}</p>
          )}
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Email field */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-[var(--login-text)]">
              {texts.emailLabel || 'Email'}
            </label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => {
                setFormData({ ...formData, email: e.target.value })
                setErrors({ ...errors, email: undefined })
              }}
              className={cn(
                "w-full px-3 py-2 border rounded-[var(--login-border-radius)] focus:outline-none focus:ring-2 focus:ring-[var(--login-primary)]",
                errors.email && "border-red-500"
              )}
              placeholder="name@example.com"
              autoFocus={autoFocus}
              disabled={disabled || isSubmitting}
            />
            {errors.email && (
              <p className="text-sm text-red-500">{errors.email}</p>
            )}
          </div>

          {/* Password field */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-[var(--login-text)]">
              {texts.passwordLabel || 'Password'}
            </label>
            <input
              type="password"
              value={formData.password}
              onChange={(e) => {
                setFormData({ ...formData, password: e.target.value })
                setErrors({ ...errors, password: undefined })
              }}
              className={cn(
                "w-full px-3 py-2 border rounded-[var(--login-border-radius)] focus:outline-none focus:ring-2 focus:ring-[var(--login-primary)]",
                errors.password && "border-red-500"
              )}
              placeholder="••••••••"
              disabled={disabled || isSubmitting}
            />
            {errors.password && (
              <p className="text-sm text-red-500">{errors.password}</p>
            )}
          </div>

          {/* Remember me & Forgot password */}
          {(features.rememberMe || features.forgotPassword) && (
            <div className="flex items-center justify-between">
              {features.rememberMe && (
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={formData.rememberMe}
                    onChange={(e) => setFormData({ ...formData, rememberMe: e.target.checked })}
                    className="mr-2"
                    disabled={disabled || isSubmitting}
                  />
                  <span className="text-sm text-gray-600">
                    {texts.rememberMeLabel || 'Remember me'}
                  </span>
                </label>
              )}
              {features.forgotPassword && (
                <button
                  type="button"
                  onClick={onForgotPassword}
                  className="text-sm text-[var(--login-primary)] hover:underline"
                  disabled={disabled || isSubmitting}
                >
                  {texts.forgotPasswordLink || 'Forgot password?'}
                </button>
              )}
            </div>
          )}

          {/* Submit button */}
          <button
            type="submit"
            disabled={disabled || isSubmitting}
            className={cn(
              "w-full py-2 px-4 bg-[var(--login-primary)] text-white rounded-[var(--login-border-radius)] font-medium",
              "hover:opacity-90 transition-opacity",
              "disabled:opacity-50 disabled:cursor-not-allowed"
            )}
          >
            {isSubmitting ? 'Loading...' : (texts.submitButton || 'Sign in')}
          </button>
        </form>

        {/* Social login */}
        {features.socialLogin && (
          <>
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-2 bg-[var(--login-background)] text-gray-500">
                  {texts.orContinueWith || 'Or continue with'}
                </span>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              {(Array.isArray(features.socialLogin) ? features.socialLogin : ['google', 'github']).map((provider) => (
                <button
                  key={provider}
                  type="button"
                  onClick={() => handleSocialLogin(provider)}
                  disabled={disabled || isSubmitting}
                  className={cn(
                    "flex items-center justify-center py-2 px-4 border rounded-[var(--login-border-radius)]",
                    "hover:bg-gray-50 transition-colors",
                    "disabled:opacity-50 disabled:cursor-not-allowed"
                  )}
                >
                  {provider.charAt(0).toUpperCase() + provider.slice(1)}
                </button>
              ))}
            </div>
          </>
        )}

        {/* Footer */}
        {footer}
      </div>
    </div>
  )
}

// Export types
export type { LoginFormProps, LoginData, LoginFormTheme, LoginFormFeatures, LoginFormTexts } from './types'