import React, { memo, useState, useEffect, useCallback } from 'react';
import type { ModelResponse, RoomResponse, RoomAiResponse, RoomAiUpsertRequest } from '@/client';
import { aiList, aiUpsert, aiDelete, modelList } from '@/client';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Loader2, Plus, Trash2, Bot, ChevronDown, ChevronRight } from 'lucide-react';
import { toast } from 'sonner';

interface RoomSettingsPanelProps {
  room: RoomResponse;
  onUpdate: (name: string, isPublic: boolean) => Promise<void>;
  onClose: () => void;
  isPending: boolean;
}

export const RoomSettingsPanel = memo(function RoomSettingsPanel({
  room,
  onUpdate,
  onClose,
  isPending,
}: RoomSettingsPanelProps) {
  const [name, setName] = useState(room.room_name ?? '');
  const [isPublic, setIsPublic] = useState(!!room.public);

  // Sync form when room prop changes (e.g., user switched to a different room)
  useEffect(() => {
    setName(room.room_name ?? '');
    setIsPublic(!!room.public);
  }, [room.id, room.room_name, room.public]);

  // AI section state
  const [aiConfigs, setAiConfigs] = useState<RoomAiResponse[]>([]);
  const [aiConfigsLoading, setAiConfigsLoading] = useState(false);
  const [showAiAddDialog, setShowAiAddDialog] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);

  // Add AI form state
  const [availableModels, setAvailableModels] = useState<ModelResponse[]>([]);
  const [modelsLoading, setModelsLoading] = useState(false);
  const [selectedModelId, setSelectedModelId] = useState('');
  const [temperature, setTemperature] = useState('');
  const [maxTokens, setMaxTokens] = useState('');
  const [historyLimit, setHistoryLimit] = useState('');
  const [systemPrompt, setSystemPrompt] = useState('');
  const [useExact, setUseExact] = useState(false);
  const [think, setThink] = useState(false);
  const [stream, setStream] = useState(true);
  const [agentType, setAgentType] = useState('chat');
  const [isAddingAi, setIsAddingAi] = useState(false);

  const handleSave = async () => {
    if (!name.trim()) return;
    try {
      await onUpdate(name.trim(), isPublic);
      toast.success('Room updated');
      onClose();
    } catch {
      toast.error('Failed to update room');
    }
  };

  // Load AI configs
  const loadAiConfigs = useCallback(async () => {
    setAiConfigsLoading(true);
    try {
      const resp = await aiList({ path: { room_id: room.id } });
      const inner = resp.data as { data?: RoomAiResponse[] } | undefined;
      setAiConfigs(Array.isArray(inner?.data) ? inner.data : []);
    } catch {
      // ignore
    } finally {
      setAiConfigsLoading(false);
    }
  }, [room.id]);

  // Load available models
  const loadModels = useCallback(async () => {
    setModelsLoading(true);
    try {
      const resp = await modelList({});
      const inner = resp.data as { data?: ModelResponse[] } | undefined;
      setAvailableModels(Array.isArray(inner?.data) ? inner.data : []);
    } catch {
      toast.error('Failed to load models');
    } finally {
      setModelsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadAiConfigs();
    loadModels();
  }, [loadAiConfigs, loadModels]);

  const openAddDialog = () => {
    setSelectedModelId('');
    setTemperature('');
    setMaxTokens('');
    setHistoryLimit('');
    setSystemPrompt('');
    setUseExact(false);
    setThink(false);
    setStream(true);
    setAgentType('chat');
    setShowAdvanced(false);
    setShowAiAddDialog(true);
    loadModels();
  };

  const handleAddAi = async () => {
    if (!selectedModelId) {
      toast.error('Please select a model');
      return;
    }
    setIsAddingAi(true);
    try {
      const body: RoomAiUpsertRequest = {
        model: selectedModelId,
        temperature: temperature ? parseFloat(temperature) : undefined,
        max_tokens: maxTokens ? parseInt(maxTokens) : undefined,
        history_limit: historyLimit ? parseInt(historyLimit) : undefined,
        system_prompt: systemPrompt || undefined,
        use_exact: useExact,
        think,
        stream,
        agent_type: agentType || undefined,
      };
      await aiUpsert({
        path: { room_id: room.id },
        body,
      });
      toast.success('AI model added');
      setShowAiAddDialog(false);
      loadAiConfigs();
    } catch {
      toast.error('Failed to add AI model');
    } finally {
      setIsAddingAi(false);
    }
  };

  const handleDeleteAi = async (modelId: string) => {
    try {
      await aiDelete({ path: { room_id: room.id, model_id: modelId } });
      toast.success('AI model removed');
      setAiConfigs((prev) => prev.filter((c) => c.model !== modelId));
    } catch {
      toast.error('Failed to remove AI model');
    }
  };

  return (
    <aside
      className="flex flex-col h-full"
      style={{ background: 'var(--room-bg)', borderColor: 'var(--room-border)' }}
    >
      <header
        className="flex h-12 items-center border-b px-4 shrink-0"
        style={{ borderColor: 'var(--room-border)' }}
      >
        <p className="text-sm font-semibold" style={{ color: 'var(--room-text)' }}>Room Settings</p>
      </header>

      <div className="flex-1 overflow-y-auto p-4 space-y-6">
        {/* General Section */}
        <section className="space-y-3">
          <h3
            className="text-xs font-semibold uppercase tracking-wide"
            style={{ color: 'var(--room-text-muted)' }}
          >
            General
          </h3>

          <div className="space-y-2">
            <Label className="text-sm" style={{ color: 'var(--room-text)' }}>Room name</Label>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Room name"
              className="border-border/70 bg-muted/30"
              style={{
                background: 'var(--room-bg)',
                borderColor: 'var(--room-border)',
                color: 'var(--room-text)',
              }}
            />
          </div>

          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium" style={{ color: 'var(--room-text)' }}>Public</p>
              <p className="text-xs" style={{ color: 'var(--room-text-muted)' }}>Visible to all project members</p>
            </div>
            <Switch
              checked={isPublic}
              onCheckedChange={setIsPublic}
              aria-label="Public room visibility"
              style={{ '--room-accent': 'var(--room-accent)' } as React.CSSProperties}
            />
          </div>

          <Button
            onClick={handleSave}
            disabled={!name.trim() || isPending}
            className="w-full border-none"
            style={{ background: 'var(--room-accent)', color: 'var(--accent-fg)' }}
          >
            {isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : null}
            Save Changes
          </Button>
        </section>

        {/* AI Section */}
        <section className="space-y-3">
          <div className="flex items-center justify-between">
            <h3
              className="text-xs font-semibold uppercase tracking-wide"
              style={{ color: 'var(--room-text-muted)' }}
            >
              AI Models
            </h3>
            <Button
              variant="ghost"
              size="sm"
              className="h-7 gap-1 px-2"
              onClick={openAddDialog}
              style={{ color: 'var(--room-accent)' }}
            >
              <Plus className="h-3 w-3" />
              Add
            </Button>
          </div>

          {aiConfigsLoading ? (
            <div className="flex justify-center py-4">
              <Loader2 className="h-5 w-5 animate-spin" style={{ color: 'var(--room-text-muted)' }} />
            </div>
          ) : aiConfigs.length === 0 ? (
            <p className="text-xs py-2" style={{ color: 'var(--room-text-muted)' }}>No AI models configured</p>
          ) : (
            <div className="space-y-2">
              {aiConfigs.map((config) => (
                <div
                  key={config.model}
                  className="flex items-center justify-between rounded-md px-3 py-2"
                  style={{ border: `1px solid var(--room-border)`, background: 'var(--room-bg)' }}
                >
                  <div className="flex items-center gap-2 min-w-0">
                    <Bot className="h-4 w-4 shrink-0" style={{ color: 'var(--room-text-muted)' }} />
                    <span className="text-sm truncate" style={{ color: 'var(--room-text)' }}>
                      {availableModels.find((m) => m.id === config.model)?.name ?? config.model}
                    </span>
                    {config.stream && (
                      <span
                        className="rounded px-1 py-0.5 text-[10px] shrink-0"
                        style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}
                      >
                        streaming
                      </span>
                    )}
                    {config.think && (
                      <span
                        className="rounded px-1 py-0.5 text-[10px] shrink-0"
                        style={{ background: 'var(--accent-subtle)', color: 'var(--room-accent)' }}
                      >
                        think
                      </span>
                    )}
                    {config.agent_type === 'react' && (
                      <span
                        className="rounded px-1 py-0.5 text-[10px] shrink-0"
                        style={{ background: 'rgba(168,85,247,0.15)', color: '#c084fc' }}
                      >
                        react
                      </span>
                    )}
                  </div>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7 shrink-0"
                    style={{ color: 'var(--room-text-muted)' }}
                    onClick={() => handleDeleteAi(config.model)}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </section>
      </div>

      {/* Add AI Dialog */}
      <Dialog open={showAiAddDialog} onOpenChange={setShowAiAddDialog}>
        <DialogContent
          className="sm:max-w-[440px]"
          style={{
            background: 'var(--room-bg)',
            border: '1px solid var(--room-border)',
            color: 'var(--room-text)',
          }}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2" style={{ color: 'var(--room-text)' }}>
              <Bot className="h-4 w-4" style={{ color: 'var(--room-accent)' }} />
              Add AI Model
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 py-2">
            {/* Model selection */}
            <div className="space-y-2">
              <Label className="text-sm" style={{ color: 'var(--room-text)' }}>Model</Label>
              {modelsLoading ? (
                <div
                  className="flex items-center gap-2 h-8 px-3 rounded-md text-sm"
                  style={{ border: '1px solid var(--room-border)', color: 'var(--room-text-muted)' }}
                >
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Loading models...
                </div>
              ) : (
                <Select value={selectedModelId} onValueChange={(v) => { if (v !== null) setSelectedModelId(v); }}>
                  <SelectTrigger className="w-full" style={{ background: 'var(--room-bg)', borderColor: 'var(--room-border)', color: 'var(--room-text)' }}>
                    <SelectValue placeholder="Select a model...">
                      {selectedModelId
                        ? availableModels.find((m) => m.id === selectedModelId)?.name ?? selectedModelId
                        : null}
                    </SelectValue>
                  </SelectTrigger>
                  <SelectContent style={{ background: 'var(--room-bg)', border: '1px solid var(--room-border)' }}>
                    {availableModels.map((model) => (
                      <SelectItem key={model.id} value={model.id}>
                        <div className="flex flex-col items-start gap-0.5">
                          <span className="font-medium">{model.name}</span>
                          <span className="text-xs" style={{ color: 'var(--room-text-muted)' }}>
                            {model.capability} · {model.modality}
                          </span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>

            {/* System prompt */}
            <div className="space-y-2">
              <Label className="text-sm" style={{ color: 'var(--room-text)' }}>System Prompt</Label>
              <textarea
                className="min-h-[80px] w-full rounded-md px-3 py-2 text-sm resize-none focus-visible:outline-none focus-visible:ring-1"
                style={{
                  border: '1px solid var(--room-border)',
                  background: 'var(--room-bg)',
                  color: 'var(--room-text)',
                  '--ring-color': 'var(--room-accent)',
                } as React.CSSProperties}
                placeholder="Optional system prompt for this AI..."
                value={systemPrompt}
                onChange={(e) => setSystemPrompt(e.target.value)}
              />
            </div>

            {/* Agent type */}
            <div className="space-y-2">
              <Label className="text-sm" style={{ color: 'var(--room-text)' }}>Agent Type</Label>
              <Select value={agentType} onValueChange={(v) => { if (v !== null) setAgentType(v); }}>
                <SelectTrigger className="w-full" style={{ background: 'var(--room-bg)', borderColor: 'var(--room-border)', color: 'var(--room-text)' }}>
                  <SelectValue>
                    {agentType === 'react' ? 'ReAct (multi-step reasoning)' : 'Chat (simple)'}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent style={{ background: 'var(--room-bg)', border: '1px solid var(--room-border)' }}>
                  <SelectItem value="chat">
                    <div className="flex flex-col items-start gap-0.5">
                      <span className="font-medium">Chat</span>
                      <span className="text-xs" style={{ color: 'var(--room-text-muted)' }}>Simple single-turn response</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="react">
                    <div className="flex flex-col items-start gap-0.5">
                      <span className="font-medium">ReAct</span>
                      <span className="text-xs" style={{ color: 'var(--room-text-muted)' }}>Multi-step reasoning with tool use</span>
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Advanced settings toggle */}
            <button
              type="button"
              className="flex items-center gap-1 text-xs transition-colors"
              style={{ color: 'var(--room-text-muted)' }}
              onClick={() => setShowAdvanced((v) => !v)}
            >
              {showAdvanced ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
              Advanced options
            </button>

            {showAdvanced && (
              <div className="space-y-3 pl-1">
                {/* Temperature */}
                <div className="space-y-1">
                  <Label className="text-xs" style={{ color: 'var(--room-text)' }}>Temperature</Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    max="2"
                    placeholder="e.g. 0.7"
                    value={temperature}
                    onChange={(e) => setTemperature(e.target.value)}
                    style={{ background: 'var(--room-bg)', borderColor: 'var(--room-border)', color: 'var(--room-text)' }}
                  />
                </div>

                {/* Max tokens */}
                <div className="space-y-1">
                  <Label className="text-xs" style={{ color: 'var(--room-text)' }}>Max Tokens</Label>
                  <Input
                    type="number"
                    placeholder="e.g. 4096"
                    value={maxTokens}
                    onChange={(e) => setMaxTokens(e.target.value)}
                    style={{ background: 'var(--room-bg)', borderColor: 'var(--room-border)', color: 'var(--room-text)' }}
                  />
                </div>

                {/* History limit */}
                <div className="space-y-1">
                  <Label className="text-xs" style={{ color: 'var(--room-text)' }}>History Limit (messages)</Label>
                  <Input
                    type="number"
                    placeholder="e.g. 50"
                    value={historyLimit}
                    onChange={(e) => setHistoryLimit(e.target.value)}
                    style={{ background: 'var(--room-bg)', borderColor: 'var(--room-border)', color: 'var(--room-text)' }}
                  />
                </div>

                {/* Toggles */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label className="text-xs" style={{ color: 'var(--room-text)' }}>Use Exact</Label>
                    <Switch checked={useExact} onCheckedChange={setUseExact} size="sm" />
                  </div>
                  <div className="flex items-center justify-between">
                    <Label className="text-xs" style={{ color: 'var(--room-text)' }}>Think Mode</Label>
                    <Switch checked={think} onCheckedChange={setThink} size="sm" />
                  </div>
                  <div className="flex items-center justify-between">
                    <Label className="text-xs" style={{ color: 'var(--room-text)' }}>Streaming</Label>
                    <Switch checked={stream} onCheckedChange={setStream} size="sm" />
                  </div>
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowAiAddDialog(false)}
              style={{ borderColor: 'var(--room-border)', color: 'var(--room-text)' }}
            >
              Cancel
            </Button>
            <Button
              onClick={handleAddAi}
              disabled={!selectedModelId || isAddingAi}
              style={{ background: 'var(--room-accent)', color: 'var(--accent-fg)', border: 'none' }}
            >
              {isAddingAi ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              Add Model
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </aside>
  );
});
