import { KeyIcon, Trash2Icon } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { extractUserIdFromName } from "@/helpers/resource-names";
import useCurrentUser from "@/hooks/useCurrentUser";
import { handleError } from "@/lib/error";
import { userServiceClient } from "@/service";
import { useTranslate } from "@/utils/i18n";
import SettingGroup from "./SettingGroup";
import SettingRow from "./SettingRow";
import SettingSection from "./SettingSection";

const OpenAIKeySection = () => {
  const t = useTranslate();
  const currentUser = useCurrentUser();
  const [apiKey, setApiKey] = useState("");
  const [maskedKey, setMaskedKey] = useState<string | null>(null);
  const [hasKey, setHasKey] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // Get user ID from user name
  const userId = currentUser?.name ? extractUserIdFromName(currentUser.name) : currentUser?.id || "";

  // Load current key status on mount
  useEffect(() => {
    if (userId) {
      loadKeyStatus();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userId]);

  const loadKeyStatus = async () => {
    if (!userId) return;
    
    setIsLoading(true);
    try {
      const result = await userServiceClient.getOpenAIKey(userId);
      setHasKey(result.has_key);
      setMaskedKey(result.masked_key);
    } catch (error) {
      handleError(error, toast.error, {
        context: "Failed to load OpenAI key status",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const validateKey = (key: string): boolean => {
    if (!key || !key.trim()) {
      return false;
    }
    const trimmed = key.trim();
    if (!trimmed.startsWith("sk-")) {
      return false;
    }
    if (trimmed.length < 20 || trimmed.length > 100) {
      return false;
    }
    return true;
  };

  const handleSave = async () => {
    if (!userId) {
      toast.error("User not found");
      return;
    }

    if (!validateKey(apiKey)) {
      toast.error("Invalid OpenAI API key format. Key must start with 'sk-' and be 20-100 characters.");
      return;
    }

    setIsSaving(true);
    try {
      const result = await userServiceClient.updateOpenAIKey(userId, apiKey.trim());
      setApiKey("");
      setHasKey(true);
      setMaskedKey(result.masked_key);
      toast.success(result.message || "OpenAI API key saved successfully");
    } catch (error) {
      handleError(error, toast.error, {
        context: "Failed to save OpenAI key",
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!userId) {
      toast.error("User not found");
      return;
    }

    if (!confirm("Are you sure you want to delete your OpenAI API key? This will disable personalized embeddings.")) {
      return;
    }

    setIsDeleting(true);
    try {
      await userServiceClient.deleteOpenAIKey(userId);
      setHasKey(false);
      setMaskedKey(null);
      setApiKey("");
      toast.success("OpenAI API key deleted successfully");
    } catch (error) {
      handleError(error, toast.error, {
        context: "Failed to delete OpenAI key",
      });
    } finally {
      setIsDeleting(false);
    }
  };

  if (isLoading) {
    return (
      <SettingSection>
        <SettingGroup title="OpenAI API Key">
          <p className="text-sm text-muted-foreground">Loading...</p>
        </SettingGroup>
      </SettingSection>
    );
  }

  return (
    <SettingSection>
      <SettingGroup title="OpenAI API Key">
        <div className="flex flex-col gap-4">
          <div className="text-sm text-muted-foreground">
            Enter your OpenAI API key to enable personalized embeddings and AI features.
            Your key will be encrypted and stored securely.
          </div>

          {hasKey && maskedKey && (
            <div className="flex items-center gap-2 p-3 bg-muted rounded-md">
              <KeyIcon className="w-4 h-4 text-muted-foreground" />
              <span className="text-sm font-mono">{maskedKey}</span>
              <span className="text-xs text-muted-foreground ml-auto">Key saved</span>
            </div>
          )}

          <SettingRow label="API Key">
            <div className="flex flex-col gap-2 w-full">
              <Input
                type="password"
                placeholder="sk-..."
                value={apiKey}
                onChange={(e) => setApiKey(e.target.value)}
                className="font-mono"
                disabled={isSaving}
              />
              <div className="flex gap-2">
                <Button
                  onClick={handleSave}
                  disabled={!apiKey.trim() || !validateKey(apiKey) || isSaving}
                  size="sm"
                >
                  {isSaving ? "Saving..." : hasKey ? "Update Key" : "Save Key"}
                </Button>
                {hasKey && (
                  <Button
                    onClick={handleDelete}
                    variant="destructive"
                    size="sm"
                    disabled={isDeleting}
                  >
                    <Trash2Icon className="w-4 h-4 mr-1" />
                    {isDeleting ? "Deleting..." : "Delete"}
                  </Button>
                )}
              </div>
            </div>
          </SettingRow>

          <div className="text-xs text-muted-foreground">
            <p>• Your key is encrypted before storage</p>
            <p>• Your key takes priority over system default key</p>
            <p>• You can delete your key anytime to use system default</p>
          </div>
        </div>
      </SettingGroup>
    </SettingSection>
  );
};

export default OpenAIKeySection;

