'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Eye, EyeOff, Loader2, Sparkles, Trash2 } from 'lucide-react';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import {
  adminApi,
  type AiSettings,
  type UpdateAiSettingsPayload,
} from '@/lib/admin-api';

const UNCHANGED_SENTINEL = '__UNCHANGED__';
const DEFAULT_API_URL = 'https://api.anthropic.com/v1';
const DEFAULT_MODEL = 'claude-opus-4-5';

const PRESET_MODELS = [
  'claude-opus-4-5',
  'claude-sonnet-4-5',
  'claude-haiku-4-5',
] as const;

export default function AdminAiSettingsPage() {
  const queryClient = useQueryClient();

  const { data, isLoading, error } = useQuery<AiSettings>({
    queryKey: ['admin', 'ai-settings'],
    queryFn: () => adminApi.getAiSettings(),
    staleTime: 30_000,
  });

  const [apiUrl, setApiUrl] = React.useState<string>(DEFAULT_API_URL);
  const [apiKey, setApiKey] = React.useState<string>('');
  const [showApiKey, setShowApiKey] = React.useState(false);
  const [modelChoice, setModelChoice] = React.useState<string>(DEFAULT_MODEL);
  const [customModel, setCustomModel] = React.useState<string>('');
  const [savedBanner, setSavedBanner] = React.useState<string | null>(null);
  const [errorBanner, setErrorBanner] = React.useState<string | null>(null);

  // Hydrate form state once data loads.
  React.useEffect(() => {
    if (!data) return;
    setApiUrl(data.apiUrl || DEFAULT_API_URL);
    // If the server already has a key stored, pre-populate the sentinel so an
    // accidental "Save" without editing does NOT overwrite the existing key.
    setApiKey(data.hasApiKey ? UNCHANGED_SENTINEL : '');
    const currentModel = data.model || DEFAULT_MODEL;
    if ((PRESET_MODELS as readonly string[]).includes(currentModel)) {
      setModelChoice(currentModel);
      setCustomModel('');
    } else {
      setModelChoice('__custom__');
      setCustomModel(currentModel);
    }
  }, [data]);

  const mutation = useMutation({
    mutationFn: (payload: UpdateAiSettingsPayload) => adminApi.updateAiSettings(payload),
    onSuccess: (result) => {
      queryClient.setQueryData(['admin', 'ai-settings'], result);
      setSavedBanner('Đã lưu cài đặt AI');
      setErrorBanner(null);
      // Re-hydrate sentinel so the input reflects "key stored, untouched".
      if (result.hasApiKey) setApiKey(UNCHANGED_SENTINEL);
      else setApiKey('');
      setTimeout(() => setSavedBanner(null), 4000);
    },
    onError: (err) => {
      setErrorBanner(err instanceof Error ? err.message : 'Lưu cài đặt thất bại');
      setSavedBanner(null);
    },
  });

  const effectiveModel = modelChoice === '__custom__' ? customModel.trim() : modelChoice;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorBanner(null);
    setSavedBanner(null);

    if (!apiUrl.trim()) {
      setErrorBanner('API Base URL không được để trống');
      return;
    }
    if (!effectiveModel) {
      setErrorBanner('Vui lòng chọn hoặc nhập model');
      return;
    }

    const payload: UpdateAiSettingsPayload = {
      apiUrl: apiUrl.trim(),
      model: effectiveModel,
    };

    // Only send apiKey when the user actually changed it. `UNCHANGED_SENTINEL`
    // tells the backend to leave the stored key alone.
    if (apiKey !== UNCHANGED_SENTINEL) {
      payload.apiKey = apiKey;
    }

    mutation.mutate(payload);
  };

  const handleClearKey = () => {
    if (!data?.hasApiKey) return;
    setErrorBanner(null);
    setSavedBanner(null);
    mutation.mutate({ apiKey: '' });
    setApiKey('');
  };

  if (isLoading) {
    return (
      <div className="flex min-h-[40vh] items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-md border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive">
        {error instanceof Error ? error.message : 'Không thể tải cài đặt AI'}
      </div>
    );
  }

  const maskedPlaceholder =
    data?.apiKeyMasked ?? 'sk-ant-...xxxx';

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Cài đặt AI</h1>
        <p className="text-sm text-muted-foreground">
          Cấu hình API Claude (Anthropic) cho các tính năng AI của nền tảng.
        </p>
      </div>

      {savedBanner && (
        <div className="rounded-md border border-emerald-500/50 bg-emerald-500/10 px-4 py-2 text-sm text-emerald-700 dark:text-emerald-400">
          {savedBanner}
        </div>
      )}
      {errorBanner && (
        <div className="rounded-md border border-destructive/50 bg-destructive/10 px-4 py-2 text-sm text-destructive">
          {errorBanner}
        </div>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-xl">
            <Sparkles className="h-5 w-5 text-primary" />
            Kết nối Claude (Anthropic)
          </CardTitle>
          <p className="text-sm text-muted-foreground">
            Key và URL dùng cho AI nhận định, AI định giá BĐS.
          </p>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-5">
            <div className="space-y-2">
              <Label htmlFor="apiUrl">API Base URL</Label>
              <Input
                id="apiUrl"
                type="url"
                value={apiUrl}
                onChange={(e) => setApiUrl(e.target.value)}
                placeholder={DEFAULT_API_URL}
                required
              />
              <p className="text-xs text-muted-foreground">
                Mặc định: {DEFAULT_API_URL}
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="apiKey">API Key</Label>
              <div className="flex gap-2">
                <div className="relative flex-1">
                  <Input
                    id="apiKey"
                    type={showApiKey ? 'text' : 'password'}
                    value={apiKey}
                    onChange={(e) => setApiKey(e.target.value)}
                    placeholder={data?.hasApiKey ? maskedPlaceholder : 'sk-ant-api03-...'}
                    autoComplete="off"
                    className="pr-10"
                  />
                  <button
                    type="button"
                    onClick={() => setShowApiKey((v) => !v)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    aria-label={showApiKey ? 'Ẩn key' : 'Hiện key'}
                  >
                    {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {data?.hasApiKey && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={handleClearKey}
                    disabled={mutation.isPending}
                    title="Xoá key đã lưu"
                  >
                    <Trash2 className="mr-1 h-4 w-4" />
                    Xoá key
                  </Button>
                )}
              </div>
              {data?.hasApiKey ? (
                <p className="text-xs text-muted-foreground">
                  Key hiện tại: <span className="font-mono">{data.apiKeyMasked}</span>. Để giữ
                  nguyên, không sửa trường này.
                </p>
              ) : (
                <p className="text-xs text-muted-foreground">
                  Chưa có key — dán key mới từ console Anthropic.
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="model">Model</Label>
              <Select
                id="model"
                value={modelChoice}
                onChange={(e) => setModelChoice(e.target.value)}
              >
                {PRESET_MODELS.map((m) => (
                  <option key={m} value={m}>
                    {m}
                  </option>
                ))}
                <option value="__custom__">Khác...</option>
              </Select>
              {modelChoice === '__custom__' && (
                <Input
                  value={customModel}
                  onChange={(e) => setCustomModel(e.target.value)}
                  placeholder="claude-xxxxx"
                />
              )}
            </div>

            <Button
              type="submit"
              className="w-full"
              disabled={mutation.isPending}
            >
              {mutation.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Đang lưu...
                </>
              ) : (
                'Lưu cài đặt'
              )}
            </Button>
          </form>
        </CardContent>
      </Card>

      <div className="rounded-md border bg-muted/30 p-4 text-xs text-muted-foreground">
        Key được lưu mã hoá trong database và chỉ truy cập được bởi quản trị viên.
        {data?.updatedAt && (
          <span className="ml-2">
            · Cập nhật lần cuối:{' '}
            {new Date(data.updatedAt).toLocaleString('vi-VN')}
          </span>
        )}
      </div>
    </div>
  );
}
