"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { ollamaClient, OLLAMA_CLOUD_MODELS } from "@/services/ollama-client"
import { seriesGenerator } from "@/services/series-generator"
import { Settings, Key, CheckCircle, AlertCircle, ExternalLink, Save } from "lucide-react"

export default function OllamaSettings() {
  const [apiKey, setApiKey] = useState("")
  const [isSaved, setIsSaved] = useState(false)
  const [isChecking, setIsChecking] = useState(false)
  const [status, setStatus] = useState<{
    available: boolean
    modelsAvailable: string[]
    apiKeySet: boolean
    error?: string
  } | null>(null)

  useEffect(() => {
    // Check current API key status
    const keyInfo = ollamaClient.getApiKeyInfo()
    if (keyInfo.isSet) {
      setApiKey(keyInfo.source === 'environment' ? '•••••••••••••••••••••••' : keyInfo.source === 'localStorage' ? '••••••••••••••••••••' : '')
      checkStatus()
    }
  }, [])

  const checkStatus = async () => {
    setIsChecking(true)
    setStatus(null)

    try {
      const status = await seriesGenerator.checkOllamaStatus()
      setStatus(status)
    } catch (error) {
      setStatus({
        available: false,
        modelsAvailable: [],
        apiKeySet: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      })
    } finally {
      setIsChecking(false)
    }
  }

  const handleSaveKey = () => {
    if (!apiKey.trim()) {
      return
    }

    ollamaClient.setApiKey(apiKey.trim(), true)
    setIsSaved(true)
    setTimeout(() => setIsSaved(false), 2000)
    checkStatus()
  }

  const handleClearKey = () => {
    ollamaClient.clearApiKey()
    setApiKey("")
    setStatus(null)
  }

  const getApiKeyDisplay = () => {
    if (!apiKey) return ""
    
    // Mask API key for display
    if (apiKey.length <= 8) return '••••••'
    return apiKey.substring(0, 4) + '••••••' + apiKey.substring(apiKey.length - 4)
  }

  return (
    <div className="container mx-auto px-4 py-16">
      <div className="max-w-2xl mx-auto space-y-8">
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            <Settings className="h-12 w-12 text-blue-600" />
          </div>
          <h2 className="text-3xl font-bold mb-4">Ollama Cloud Settings</h2>
          <p className="text-gray-600">
            Configure Ollama Cloud API key for AI-powered story generation
          </p>
          <div className="flex justify-center gap-2">
            <Button variant="outline" size="sm" asChild>
              <a 
                href="https://ollama.com" 
                target="_blank" 
                rel="noopener noreferrer"
                className="flex items-center"
              >
                <ExternalLink className="mr-2 h-4 w-4" />
                Get Free API Key
              </a>
            </Button>
            <Button 
              variant="outline" 
              size="sm"
              onClick={checkStatus}
              disabled={isChecking}
            >
              {isChecking ? 'Checking...' : 'Check Status'}
            </Button>
          </div>
        </div>

        {/* API Key Input */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Key className="h-5 w-5" />
              API Key Configuration
            </CardTitle>
            <CardDescription>
              Your API key will be stored securely and used for AI story generation.
              Get a free key at <a href="https://ollama.com" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">ollama.com</a>
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-2 block">
                Ollama API Key
              </label>
              <div className="relative">
                <Input
                  type="password"
                  placeholder="Enter your Ollama Cloud API key..."
                  value={apiKey}
                  onChange={(e) => setApiKey(e.target.value)}
                  className="pr-10"
                />
                <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                  {apiKey && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={handleClearKey}
                      className="h-8 px-2"
                    >
                      Clear
                    </Button>
                  )}
                </div>
              </div>
              <div className="text-xs text-gray-500">
                {apiKey ? `Key: ${getApiKeyDisplay()}` : 'No key set'}
              </div>
            </div>

            <div className="flex gap-2">
              <Button 
                onClick={handleSaveKey}
                disabled={!apiKey.trim() || isSaved}
                className="flex-1"
              >
                <Save className="mr-2 h-4 w-4" />
                {isSaved ? 'Saved!' : 'Save Key'}
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Status Display */}
        {status && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                {status.available ? (
                  <CheckCircle className="h-5 w-5 text-green-600" />
                ) : (
                  <AlertCircle className="h-5 w-5 text-red-600" />
                )}
                Ollama Cloud Status
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {status.error ? (
                <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                  <AlertCircle className="h-4 w-4 inline mr-2" />
                  {status.error}
                </div>
              ) : (
                <div className="space-y-3">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium">Connection Status:</span>
                    <span className={`px-2 py-1 rounded text-xs ${
                      status.available 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-red-100 text-red-800'
                    }`}>
                      {status.available ? 'Connected' : 'Disconnected'}
                    </span>
                  </div>

                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium">API Key Status:</span>
                    <span className={`px-2 py-1 rounded text-xs ${
                      status.apiKeySet 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-yellow-100 text-yellow-800'
                    }`}>
                      {status.apiKeySet ? 'Set' : 'Not Set'}
                    </span>
                  </div>

                  {status.modelsAvailable && status.modelsAvailable.length > 0 && (
                    <div>
                      <span className="text-sm font-medium block mb-2">Available Models:</span>
                      <div className="space-y-1">
                        {status.modelsAvailable.map(model => (
                          <div key={model} className="text-xs bg-gray-100 text-gray-800 px-2 py-1 rounded">
                            {model}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* Available Models */}
        <Card>
          <CardHeader>
            <CardTitle>Supported Cloud Models</CardTitle>
            <CardDescription>
              Free and paid models available through Ollama Cloud
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-2 gap-4">
              {Object.entries(OLLAMA_CLOUD_MODELS).map(([model, description]) => (
                <div key={model} className="space-y-2">
                  <div className="flex items-center gap-2">
                    <span className="font-mono text-sm bg-gray-100 px-2 py-1 rounded">
                      {model}
                    </span>
                    <span className="text-sm text-gray-600 truncate">
                      {description.split(' - ')[0]}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500">
                    {description.split(' - ')[1]}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Instructions */}
        <Card>
          <CardHeader>
            <CardTitle>Setup Instructions</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3 text-sm">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-blue-600 font-bold">1</span>
              </div>
              <div>
                <p className="font-medium">Get Free API Key</p>
                <p className="text-gray-600">Visit <a href="https://ollama.com" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">ollama.com</a> and create a free account</p>
              </div>
            </div>
            
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-blue-600 font-bold">2</span>
              </div>
              <div>
                <p className="font-medium">Copy API Key</p>
                <p className="text-gray-600">Enter your API key in the field above and click "Save Key"</p>
              </div>
            </div>
            
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-blue-600 font-bold">3</span>
              </div>
              <div>
                <p className="font-medium">Start Creating Stories</p>
                <p className="text-gray-600">Use the Series Creator to generate AI-powered visual stories</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}