'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { Bot, Loader2, Zap } from 'lucide-react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

const formSchema = z.object({
  ai_enabled: z.boolean(),
  ai_provider: z.string(),
  ai_model: z.string(),
  ai_send_descriptions: z.boolean(),
  openai_api_key: z.string().optional(),
})

type FormValues = z.infer<typeof formSchema>

interface AISettingsFormProps {
  settings: {
    ai_enabled?: string
    ai_provider?: string
    ai_model?: string
    ai_send_descriptions?: string
    openai_api_key?: string
  }
}

export function AISettingsForm({ settings }: AISettingsFormProps) {
  const utils = trpc.useUtils()

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      ai_enabled: settings.ai_enabled === 'true',
      ai_provider: settings.ai_provider || 'openai',
      ai_model: settings.ai_model || 'gpt-4o',
      ai_send_descriptions: settings.ai_send_descriptions === 'true',
      openai_api_key: '',
    },
  })

  const updateSettings = trpc.settings.updateMultiple.useMutation({
    onSuccess: () => {
      toast.success('AI settings saved successfully')
      utils.settings.getByCategory.invalidate({ category: 'AI' })
    },
    onError: (error) => {
      toast.error(`Failed to save settings: ${error.message}`)
    },
  })

  const testConnection = trpc.settings.testAIConnection.useMutation({
    onSuccess: (result) => {
      if (result.success) {
        toast.success('AI connection successful')
      } else {
        toast.error(`Connection failed: ${result.error}`)
      }
    },
    onError: (error) => {
      toast.error(`Test failed: ${error.message}`)
    },
  })

  const onSubmit = (data: FormValues) => {
    const settingsToUpdate = [
      { key: 'ai_enabled', value: String(data.ai_enabled) },
      { key: 'ai_provider', value: data.ai_provider },
      { key: 'ai_model', value: data.ai_model },
      { key: 'ai_send_descriptions', value: String(data.ai_send_descriptions) },
    ]

    // Only update API key if a new value was entered
    if (data.openai_api_key && data.openai_api_key.trim()) {
      settingsToUpdate.push({ key: 'openai_api_key', value: data.openai_api_key })
    }

    updateSettings.mutate({ settings: settingsToUpdate })
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="ai_enabled"
          render={({ field }) => (
            <FormItem className="flex items-center justify-between rounded-lg border p-4">
              <div className="space-y-0.5">
                <FormLabel className="text-base">Enable AI Features</FormLabel>
                <FormDescription>
                  Use AI to suggest optimal jury-project assignments
                </FormDescription>
              </div>
              <FormControl>
                <Switch
                  checked={field.value}
                  onCheckedChange={field.onChange}
                />
              </FormControl>
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="ai_provider"
          render={({ field }) => (
            <FormItem>
              <FormLabel>AI Provider</FormLabel>
              <Select onValueChange={field.onChange} defaultValue={field.value}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select provider" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  <SelectItem value="openai">OpenAI</SelectItem>
                </SelectContent>
              </Select>
              <FormDescription>
                AI provider for smart assignment suggestions
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="ai_model"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Model</FormLabel>
              <Select onValueChange={field.onChange} defaultValue={field.value}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select model" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  <SelectItem value="gpt-4o">GPT-4o (Recommended)</SelectItem>
                  <SelectItem value="gpt-4o-mini">GPT-4o Mini</SelectItem>
                  <SelectItem value="gpt-5">GPT-5</SelectItem>
                  <SelectItem value="gpt-5-mini">GPT-5 Mini</SelectItem>
                  <SelectItem value="o3">o3</SelectItem>
                  <SelectItem value="o3-mini">o3 Mini</SelectItem>
                  <SelectItem value="o4-mini">o4 Mini</SelectItem>
                  <SelectItem value="gpt-4-turbo">GPT-4 Turbo</SelectItem>
                  <SelectItem value="gpt-4">GPT-4</SelectItem>
                </SelectContent>
              </Select>
              <FormDescription>
                OpenAI model to use for AI features
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="openai_api_key"
          render={({ field }) => (
            <FormItem>
              <FormLabel>API Key</FormLabel>
              <FormControl>
                <Input
                  type="password"
                  placeholder={settings.openai_api_key ? '••••••••' : 'Enter API key'}
                  {...field}
                />
              </FormControl>
              <FormDescription>
                Your OpenAI API key. Leave blank to keep the existing key.
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="ai_send_descriptions"
          render={({ field }) => (
            <FormItem className="flex items-center justify-between rounded-lg border p-4">
              <div className="space-y-0.5">
                <FormLabel className="text-base">Send Project Descriptions</FormLabel>
                <FormDescription>
                  Include anonymized project descriptions in AI requests for better matching
                </FormDescription>
              </div>
              <FormControl>
                <Switch
                  checked={field.value}
                  onCheckedChange={field.onChange}
                />
              </FormControl>
            </FormItem>
          )}
        />

        <div className="flex gap-2">
          <Button
            type="submit"
            disabled={updateSettings.isPending}
          >
            {updateSettings.isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Bot className="mr-2 h-4 w-4" />
                Save AI Settings
              </>
            )}
          </Button>
          <Button
            type="button"
            variant="outline"
            onClick={() => testConnection.mutate()}
            disabled={testConnection.isPending}
          >
            {testConnection.isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Testing...
              </>
            ) : (
              <>
                <Zap className="mr-2 h-4 w-4" />
                Test Connection
              </>
            )}
          </Button>
        </div>
      </form>
    </Form>
  )
}
