'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { ArrowLeft, Settings, Loader2, Save } from 'lucide-react';
import { toast } from 'sonner';

interface SettingEntry {
  value: any;
  description: string;
}

export default function WorkflowSettingsPage() {
  const [settings, setSettings] = useState<Record<string, SettingEntry>>({});
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [modified, setModified] = useState<Record<string, any>>({});

  useEffect(() => { loadSettings(); }, []);

  const loadSettings = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/workflow/settings');
      if (res.ok) {
        setSettings(await res.json());
        setModified({});
      }
    } catch { toast.error('Failed to load settings'); }
    finally { setIsLoading(false); }
  };

  const getValue = (key: string): any => {
    if (key in modified) return modified[key];
    return settings[key]?.value;
  };

  const setValue = (key: string, value: any) => {
    setModified({ ...modified, [key]: value });
  };

  const handleSave = async () => {
    if (Object.keys(modified).length === 0) return;
    setIsSaving(true);
    try {
      const res = await fetch('/api/workflow/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(modified),
      });
      if (res.ok) {
        toast.success('Settings saved');
        setSettings(await res.json());
        setModified({});
      }
    } catch { toast.error('Failed to save settings'); }
    finally { setIsSaving(false); }
  };

  if (isLoading) {
    return (
      <div className="container mx-auto p-6 flex justify-center py-20">
        <Loader2 className="w-6 h-6 animate-spin" />
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/workflow">
            <Button variant="ghost" size="sm">
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back
            </Button>
          </Link>
          <Settings className="w-6 h-6" />
          <div>
            <h1 className="text-2xl font-bold">Workflow Settings</h1>
            <p className="text-sm text-muted-foreground">Configure AI providers, thresholds, and behavior</p>
          </div>
        </div>
        {Object.keys(modified).length > 0 && (
          <Button onClick={handleSave} disabled={isSaving}>
            {isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
            Save Changes
          </Button>
        )}
      </div>

      {/* Engine Control */}
      <Card>
        <CardHeader>
          <CardTitle>Engine Control</CardTitle>
          <CardDescription>Master enable/disable for the workflow engine</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <Label>Workflow Engine</Label>
              <p className="text-sm text-muted-foreground">When enabled, new tickets are automatically classified</p>
            </div>
            <Switch
              checked={getValue('workflow_engine_enabled') ?? false}
              onCheckedChange={(v) => setValue('workflow_engine_enabled', v)}
            />
          </div>
        </CardContent>
      </Card>

      {/* AI Provider Config */}
      <Card>
        <CardHeader>
          <CardTitle>AI Provider Configuration</CardTitle>
          <CardDescription>Configure API keys and models for AI-assisted classification</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-2">
            <Label>Default AI Provider</Label>
            <Select value={getValue('default_ai_provider') || 'openai'} onValueChange={(v) => setValue('default_ai_provider', v)}>
              <SelectTrigger className="w-60"><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="openai">OpenAI</SelectItem>
                <SelectItem value="anthropic">Anthropic</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <Separator />

          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-4">
              <h4 className="font-medium">OpenAI</h4>
              <div className="space-y-2">
                <Label>API Key</Label>
                <Input
                  type="password"
                  value={getValue('openai_api_key') || ''}
                  onChange={(e) => setValue('openai_api_key', e.target.value)}
                  placeholder="sk-..."
                />
              </div>
              <div className="space-y-2">
                <Label>Model</Label>
                <Input
                  value={getValue('openai_model') || 'gpt-4o'}
                  onChange={(e) => setValue('openai_model', e.target.value)}
                />
              </div>
            </div>

            <div className="space-y-4">
              <h4 className="font-medium">Anthropic</h4>
              <div className="space-y-2">
                <Label>API Key</Label>
                <Input
                  type="password"
                  value={getValue('anthropic_api_key') || ''}
                  onChange={(e) => setValue('anthropic_api_key', e.target.value)}
                  placeholder="sk-ant-..."
                />
              </div>
              <div className="space-y-2">
                <Label>Model</Label>
                <Input
                  value={getValue('anthropic_model') || 'claude-sonnet-4-20250514'}
                  onChange={(e) => setValue('anthropic_model', e.target.value)}
                />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* AI Feature Toggles */}
      <Card>
        <CardHeader>
          <CardTitle>AI Feature Toggles</CardTitle>
          <CardDescription>Control when AI is used during triage</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {[
            { key: 'ai_for_title_cleanup', label: 'Title Cleanup', desc: 'Use AI to clean up messy ticket titles (email subjects, long titles)' },
            { key: 'ai_for_description_rewrite', label: 'Description Rewrite', desc: 'Use AI to restructure unstructured ticket descriptions' },
            { key: 'ai_for_ambiguous_classification', label: 'Ambiguous Classification', desc: 'Use AI when robotic classifier has no confident match' },
            { key: 'ai_for_troubleshooting', label: 'Troubleshooting Steps', desc: 'Generate AI troubleshooting steps for incident tickets' },
          ].map(({ key, label, desc }) => (
            <div key={key} className="flex items-center justify-between">
              <div>
                <Label>{label}</Label>
                <p className="text-sm text-muted-foreground">{desc}</p>
              </div>
              <Switch
                checked={getValue(key) ?? true}
                onCheckedChange={(v) => setValue(key, v)}
              />
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Processing Config */}
      <Card>
        <CardHeader>
          <CardTitle>Processing Configuration</CardTitle>
          <CardDescription>Thresholds, delays, and retry settings</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label>Confidence Threshold</Label>
              <p className="text-xs text-muted-foreground">Minimum confidence to skip AI classification</p>
              <Select
                value={getValue('classification_confidence_threshold') || 'medium'}
                onValueChange={(v) => setValue('classification_confidence_threshold', v)}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="high">High (AI for medium + low)</SelectItem>
                  <SelectItem value="medium">Medium (AI only for low)</SelectItem>
                  <SelectItem value="low">Low (AI rarely used)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Autotask Update Delay (ms)</Label>
              <p className="text-xs text-muted-foreground">Delay before writing back to Autotask to avoid WF rule conflicts</p>
              <Input
                type="number"
                value={getValue('autotask_update_delay_ms') ?? 30000}
                onChange={(e) => setValue('autotask_update_delay_ms', parseInt(e.target.value))}
              />
            </div>

            <div className="space-y-2">
              <Label>Max AI Retries</Label>
              <p className="text-xs text-muted-foreground">Max retry attempts when AI validation fails</p>
              <Input
                type="number"
                value={getValue('max_ai_retries') ?? 2}
                onChange={(e) => setValue('max_ai_retries', parseInt(e.target.value))}
              />
            </div>

            <div className="space-y-2">
              <Label>Log Retention (days)</Label>
              <p className="text-xs text-muted-foreground">Days to retain execution logs</p>
              <Input
                type="number"
                value={getValue('log_retention_days') ?? 90}
                onChange={(e) => setValue('log_retention_days', parseInt(e.target.value))}
              />
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
