"use client";

import { useEffect, useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useApiKey, useBaseUrl, useModelName, useSettingsActions } from '@/store/use-settings';
import { ConnectionStatus } from './connection-status';
import { SettingsService } from '@/services/settings-service';
import { ProviderManagementService } from '@/services/provider-management-service';
import { toast } from '@/hooks/use-toast';
import type { ProviderProfile } from '@/types/settings';

// Provider presets for common LLM providers
const PROVIDER_PRESETS = [
  {
    name: 'OpenAI',
    baseUrl: 'https://api.openai.com/v1',
    defaultModel: 'gpt-4o',
    description: 'Official OpenAI API endpoint',
  },
  {
    name: 'DeepSeek',
    baseUrl: 'https://api.deepseek.com/v1',
    defaultModel: 'deepseek-chat',
    description: 'DeepSeek AI - High performance, cost effective',
  },
  {
    name: 'OpenRouter',
    baseUrl: 'https://openrouter.ai/api/v1',
    defaultModel: 'anthropic/claude-3-haiku',
    description: 'Unified API for multiple providers',
  },
];

type ProviderFormMode = 'add' | 'edit';

interface ProviderFormProps {
  mode?: ProviderFormMode;
  provider?: ProviderProfile;
  onSave?: () => void;
  onCancel?: () => void;
}

export function ProviderForm({ mode, provider, onSave, onCancel }: ProviderFormProps) {
  const apiKey = useApiKey();
  const baseUrl = useBaseUrl();
  const modelName = useModelName();
  const actions = useSettingsActions();

  // Local form state for provider management modes
  const [providerName, setProviderName] = useState(provider?.name ?? '');
  const [formBaseUrl, setFormBaseUrl] = useState(provider?.baseUrl ?? baseUrl);
  const [formModelName, setFormModelName] = useState(provider?.modelName ?? modelName);
  const [formApiKey, setFormApiKey] = useState(provider?.apiKey ?? apiKey);

  const [showKey, setShowKey] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // Hydration fix for persistent store
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  // Update form when provider prop changes
  useEffect(() => {
    if (provider) {
      setProviderName(provider.name);
      setFormBaseUrl(provider.baseUrl);
      setFormModelName(provider.modelName);
      setFormApiKey(provider.apiKey);
    }
  }, [provider]);

  // Handle preset selection
  const handlePresetSelect = (preset: typeof PROVIDER_PRESETS[0]) => {
    const currentModel = mode ? formModelName : modelName;

    // Smart Preset Logic: Only overwrite model name if it's empty or matches a known default
    // This preserves custom model names (e.g., "my-finetune") when switching providers
    const isKnownDefault = PROVIDER_PRESETS.some(p => p.defaultModel === currentModel);
    const isEmpty = !currentModel || currentModel.trim() === '';
    const shouldUpdateModel = isEmpty || isKnownDefault;

    if (mode) {
      setFormBaseUrl(preset.baseUrl);
      if (shouldUpdateModel) {
        setFormModelName(preset.defaultModel);
      }
    } else {
      actions.setBaseUrl(preset.baseUrl);
      if (shouldUpdateModel) {
        actions.setModelName(preset.defaultModel);
      }
    }
  };

  // Handle save with validation (Story 4.2 AC: validate on save)
  const handleSaveWithValidation = async () => {
    // For provider management mode, validate provider name
    if (mode && !providerName.trim()) {
      toast({
        title: 'Validation Error',
        description: 'Please enter a provider name.',
        variant: 'destructive',
      });
      return;
    }

    const currentApiKey = mode ? formApiKey : apiKey;
    const currentBaseUrl = mode ? formBaseUrl : baseUrl;
    const currentModelName = mode ? formModelName : modelName;

    if (!currentApiKey || !currentBaseUrl || !currentModelName) {
      toast({
        title: 'Validation Error',
        description: 'Please fill in all fields before saving.',
        variant: 'destructive',
      });
      return;
    }

    setIsSaving(true);
    try {
      const result = await SettingsService.saveProviderSettingsWithValidation({
        apiKey: currentApiKey,
        baseUrl: currentBaseUrl,
        modelName: currentModelName,
      });

      if (result && !result.isValid) {
        // Validation failed - show error toast
        toast({
          title: 'Connection Failed',
          description: result.errorMessage || 'Could not connect to provider.',
          variant: 'destructive',
        });
        return;
      }

      if (mode === 'add') {
        // Save as new provider
        const newProviderId = ProviderManagementService.addProviderProfile({
          name: providerName,
          baseUrl: currentBaseUrl,
          apiKey: currentApiKey,
          modelName: currentModelName,
        });
        // Auto-select newly created provider
        ProviderManagementService.setActiveProvider(newProviderId);
        toast({
          title: 'Provider Added',
          description: `"${providerName}" has been added and selected as active.`,
        });
      } else if (mode === 'edit' && provider) {
        // Update existing provider
        ProviderManagementService.updateProviderProfile(provider.id, {
          name: providerName,
          baseUrl: currentBaseUrl,
          apiKey: currentApiKey,
          modelName: currentModelName,
        });
        toast({
          title: 'Provider Updated',
          description: `"${providerName}" has been updated.`,
        });
      } else {
        // Legacy mode - save to store directly
        actions.setApiKey(currentApiKey);
        actions.setBaseUrl(currentBaseUrl);
        actions.setModelName(currentModelName);
        toast({
          title: 'Settings Saved',
          description: 'Your API credentials have been verified and saved.',
        });
      }

      onSave?.();
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'An error occurred.',
        variant: 'destructive',
      });
    } finally {
      setIsSaving(false);
    }
  };

  if (!mounted) return <div className="p-4">Loading settings...</div>;

  const currentBaseUrl = mode ? formBaseUrl : baseUrl;
  const currentModelName = mode ? formModelName : modelName;
  const currentApiKey = mode ? formApiKey : apiKey;
  const handleBaseUrlChange = mode ? (e: React.ChangeEvent<HTMLInputElement>) => setFormBaseUrl(e.target.value) : (e: React.ChangeEvent<HTMLInputElement>) => actions.setBaseUrl(e.target.value);
  const handleModelNameChange = mode ? (e: React.ChangeEvent<HTMLInputElement>) => setFormModelName(e.target.value) : (e: React.ChangeEvent<HTMLInputElement>) => actions.setModelName(e.target.value);
  const handleApiKeyChange = mode ? (e: React.ChangeEvent<HTMLInputElement>) => setFormApiKey(e.target.value) : (e: React.ChangeEvent<HTMLInputElement>) => actions.setApiKey(e.target.value);

  const cardTitle = mode === 'edit' ? 'Edit Provider' : mode === 'add' ? 'Add New Provider' : 'AI Provider Settings';
  const buttonText = mode === 'edit' ? 'Update Provider' : mode === 'add' ? 'Save as New Provider' : isSaving ? 'Validating...' : 'Save & Validate';

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>{cardTitle}</CardTitle>
        <CardDescription>
          {mode
            ? 'Configure your provider profile. Your API Key is stored locally in your browser.'
            : 'Configure your own LLM provider. Your API Key is stored locally in your browser and sent directly to the provider.'}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">

        {/* Provider Name - only for add/edit modes */}
        {mode && (
          <div className="space-y-2">
            <Label htmlFor="providerName">Provider Name</Label>
            <Input
              id="providerName"
              value={providerName}
              onChange={(e) => setProviderName(e.target.value)}
              placeholder="My OpenAI Key"
            />
            <p className="text-xs text-muted-foreground">
              A label to identify this provider (e.g., "My OpenAI Key")
            </p>
          </div>
        )}

        {/* Provider Presets - hide in edit mode */}
        {mode !== 'edit' && (
          <div className="space-y-2">
            <Label>Quick Setup</Label>
            <div className="flex flex-wrap gap-2">
              {PROVIDER_PRESETS.map((preset) => (
                <button
                  key={preset.name}
                  type="button"
                  onClick={() => handlePresetSelect(preset)}
                  className="px-3 py-1 text-sm border rounded-md hover:bg-muted transition-colors"
                  title={preset.description}
                >
                  {preset.name}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Base URL */}
        <div className="space-y-2">
          <Label htmlFor="baseUrl">Base URL</Label>
          <Input
            id="baseUrl"
            value={currentBaseUrl}
            onChange={handleBaseUrlChange}
            placeholder="https://api.openai.com/v1"
            type="url"
          />
          <p className="text-xs text-muted-foreground">
            API endpoint URL (e.g., https://api.openai.com/v1)
          </p>
        </div>

        {/* Model Name */}
        <div className="space-y-2">
          <Label htmlFor="modelName">Model Name</Label>
          <Input
            id="modelName"
            value={currentModelName}
            onChange={handleModelNameChange}
            placeholder="gpt-4o"
          />
          <p className="text-xs text-muted-foreground">
            Model identifier (e.g., gpt-4o, deepseek-chat)
          </p>
        </div>

        {/* API Key */}
        <div className="space-y-2">
          <Label htmlFor="apiKey">API Key</Label>
          <div className="relative">
            <Input
              id="apiKey"
              type={showKey ? "text" : "password"}
              value={currentApiKey}
              onChange={handleApiKeyChange}
              placeholder="sk-..."
              autoComplete="off"
            />
            <button
              type="button"
              className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-500 hover:text-gray-700"
              onClick={() => setShowKey(!showKey)}
              aria-label={showKey ? "Hide API key" : "Show API key"}
            >
              {showKey ? "Hide" : "Show"}
            </button>
          </div>
          <p className="text-xs text-muted-foreground">
            Stored locally in your browser with basic encoding. Never sent to our servers.
          </p>
        </div>

        {/* Save Button with Validation */}
        <div className="flex gap-2 pt-2">
          {onCancel && (
            <Button
              onClick={onCancel}
              variant="outline"
              disabled={isSaving}
              className="flex-1"
            >
              Cancel
            </Button>
          )}
          <Button
            onClick={handleSaveWithValidation}
            disabled={isSaving}
            className={onCancel ? 'flex-1' : 'flex-1'}
          >
            {isSaving ? 'Validating...' : buttonText}
          </Button>
        </div>

        {/* Connection Status - hide in add/edit modes */}
        {!mode && <ConnectionStatus />}

      </CardContent>
    </Card>
  );
}
