'use client'

import { useState } from 'react'
import { X, Loader2, CheckCircle, XCircle, Mail } from 'lucide-react'
import type { APIProvider } from '../types/api'

interface SettingsProps {
  isOpen: boolean
  onClose: () => void
}

export function Settings({ isOpen, onClose }: SettingsProps) {
  const [isLoading, setIsLoading] = useState(false)
  const [gmailAccount, setGmailAccount] = useState('')
  const [apiProviders, setApiProviders] = useState<APIProvider[]>([
    { id: 'openai', name: 'OpenAI', apiKey: '', enabled: false, isValid: undefined },
    { id: 'google', name: 'Google Cloud Vision', apiKey: '', enabled: false, isValid: undefined },
    { id: 'aws', name: 'Amazon Textract', apiKey: '', enabled: false, isValid: undefined },
  ])

  const validateApiKey = async (provider: APIProvider) => {
    try {
      const response = await fetch('/api/validate-api-key', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          provider: provider.id,
          apiKey: provider.apiKey,
        }),
      })

      const data = await response.json()
      if (!response.ok) {
        throw new Error(data.error || 'API validation failed')
      }
      return data.success
    } catch (error) {
      console.error('API validation error:', error)
      throw error
    }
  }

  const handleApiKeyChange = (index: number, apiKey: string) => {
    const newProviders = [...apiProviders]
    newProviders[index].apiKey = apiKey
    newProviders[index].isValid = undefined // Reset validation when key changes
    newProviders[index].error = undefined; //Reset error message
    setApiProviders(newProviders)
  }

  const handleToggleProvider = (index: number) => {
    const newProviders = [...apiProviders]
    newProviders[index].enabled = !newProviders[index].enabled
    setApiProviders(newProviders)
  }

  const handleSave = async () => {
    setIsLoading(true)
    try {
      // Validate all enabled providers
      const validationPromises = apiProviders
        .filter(provider => provider.enabled)
        .map(async provider => {
          try {
            const isValid = await validateApiKey(provider)
            return { ...provider, isValid }
          } catch (error) {
            return { ...provider, isValid: false, error: error.message }
          }
        })

      const validatedProviders = await Promise.all(validationPromises)
      
      // Update providers with validation results
      const newProviders = [...apiProviders]
      validatedProviders.forEach(validated => {
        const index = newProviders.findIndex(p => p.id === validated.id)
        if (index !== -1) {
          newProviders[index] = validated
        }
      })
      
      setApiProviders(newProviders)

      // Check if all enabled providers are valid
      const allValid = validatedProviders.every(p => p.isValid)
      
      if (allValid) {
        // Save settings
        await fetch('/api/save-settings', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ 
            providers: newProviders,
            gmailAccount 
          }),
        })
        onClose()
      }
    } catch (error) {
      console.error('Error saving settings:', error)
    } finally {
      setIsLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-8 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-gray-800">Settings</h2>
          <button 
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700"
            disabled={isLoading}
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        <div className="space-y-6">
          <div className="border-b pb-4">
            <label className="flex items-center mb-2">
              <Mail className="w-5 h-5 mr-2 text-gray-600" />
              <span className="text-lg font-medium text-gray-700">Gmail Account</span>
            </label>
            <input
              type="email"
              value={gmailAccount}
              onChange={(e) => setGmailAccount(e.target.value)}
              placeholder="Enter your Gmail account"
              className="w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            />
          </div>

          {apiProviders.map((provider, index) => (
            <div key={provider.id} className="border-b pb-4">
              <div className="flex items-center justify-between mb-2">
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={provider.enabled}
                    onChange={() => handleToggleProvider(index)}
                    className="form-checkbox h-5 w-5 text-indigo-600"
                    disabled={isLoading}
                  />
                  <span className="ml-2 text-lg font-medium text-gray-700">{provider.name}</span>
                </label>
                {provider.isValid !== undefined && (
                  <div className="flex items-center gap-2">
                    {provider.isValid ? (
                      <CheckCircle className="w-5 h-5 text-green-500" />
                    ) : (
                      <XCircle className="w-5 h-5 text-red-500" />
                    )}
                  </div>
                )}
              </div>
              <div className="relative">
                <input
                  type="password"
                  value={provider.apiKey}
                  onChange={(e) => handleApiKeyChange(index, e.target.value)}
                  placeholder={`Enter ${provider.name} API Key`}
                  className={`w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-offset-2 ${
                    provider.isValid === false
                      ? 'border-red-300 focus:ring-red-500'
                      : 'border-gray-300 focus:ring-indigo-500'
                  }`}
                  disabled={!provider.enabled || isLoading}
                />
                {provider.isValid === false && (
                  <p className="text-sm text-red-600 mt-1">
                    {provider.error || 'Invalid API key'}
                  </p>
                )}
              </div>
            </div>
          ))}
        </div>

        <div className="mt-8 flex justify-end">
          <button
            onClick={handleSave}
            disabled={isLoading}
            className="bg-indigo-600 text-white px-6 py-2 rounded-md hover:bg-indigo-700 transition-colors disabled:bg-gray-400 flex items-center gap-2"
          >
            {isLoading ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Saving...
              </>
            ) : (
              'Save Settings'
            )}
          </button>
        </div>
      </div>
    </div>
  )
}

