"use client";

import { useState, useEffect } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Toggle } from "./ui/toggle";
import { ContextualHelpIcon } from "./ContextualHelpIcon";
import { useTheme } from "./ThemeProvider";
import { useRegisterModal } from "./modal/ModalStackProvider";
import { useTranslation } from "~/lib/i18n/useTranslation";

interface GeneralSettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function GeneralSettingsModal({
  isOpen,
  onClose,
}: GeneralSettingsModalProps) {
  useRegisterModal(isOpen, {
    id: "general-settings-modal",
    allowEscape: true,
    onClose,
  });
  const { t, locale, setLocale, availableLocales } = useTranslation("settings");
  const { theme, setTheme } = useTheme();
  const [activeTab, setActiveTab] = useState<"general" | "github" | "auth">(
    "general",
  );
  const [githubToken, setGithubToken] = useState("");
  const [saveFilter, setSaveFilter] = useState(false);
  const [savedFilters, setSavedFilters] = useState<any>(null);
  const [colorCodingEnabled, setColorCodingEnabled] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [message, setMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

  // Auth state
  const [authUsername, setAuthUsername] = useState("");
  const [authPassword, setAuthPassword] = useState("");
  const [authConfirmPassword, setAuthConfirmPassword] = useState("");
  const [authEnabled, setAuthEnabled] = useState(false);
  const [authHasCredentials, setAuthHasCredentials] = useState(false);
  const [authSetupCompleted, setAuthSetupCompleted] = useState(false);
  const [authLoading, setAuthLoading] = useState(false);

  // Load existing settings when modal opens
  useEffect(() => {
    if (isOpen) {
      void loadGithubToken();
      void loadSaveFilter();
      void loadSavedFilters();
      void loadAuthCredentials();
      void loadColorCodingSetting();
    }
  }, [isOpen]);

  const loadGithubToken = async () => {
    setIsLoading(true);
    try {
      const response = await fetch("/api/settings/github-token");
      if (response.ok) {
        const data = await response.json();
        setGithubToken((data.token as string) ?? "");
      }
    } catch (error) {
      console.error("Error loading GitHub token:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const loadSaveFilter = async () => {
    try {
      const response = await fetch("/api/settings/save-filter");
      if (response.ok) {
        const data = await response.json();
        setSaveFilter((data.enabled as boolean) ?? false);
      }
    } catch (error) {
      console.error("Error loading save filter setting:", error);
    }
  };

  const saveSaveFilter = async (enabled: boolean) => {
    try {
      const response = await fetch("/api/settings/save-filter", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ enabled }),
      });

      if (response.ok) {
        setSaveFilter(enabled);
        setMessage({ type: "success", text: "Save filter setting updated!" });

        // If disabling save filters, clear saved filters
        if (!enabled) {
          await clearSavedFilters();
        }
      } else {
        const errorData = await response.json();
        setMessage({
          type: "error",
          text: errorData.error ?? "Failed to save setting",
        });
      }
    } catch {
      setMessage({ type: "error", text: "Failed to save setting" });
    }
  };

  const loadSavedFilters = async () => {
    try {
      const response = await fetch("/api/settings/filters");
      if (response.ok) {
        const data = await response.json();
        setSavedFilters(data.filters);
      }
    } catch (error) {
      console.error("Error loading saved filters:", error);
    }
  };

  const clearSavedFilters = async () => {
    try {
      const response = await fetch("/api/settings/filters", {
        method: "DELETE",
      });

      if (response.ok) {
        setSavedFilters(null);
        setMessage({ type: "success", text: "Saved filters cleared!" });
      } else {
        const errorData = await response.json();
        setMessage({
          type: "error",
          text: errorData.error ?? "Failed to clear filters",
        });
      }
    } catch {
      setMessage({ type: "error", text: "Failed to clear filters" });
    }
  };

  const saveGithubToken = async () => {
    setIsSaving(true);
    setMessage(null);

    try {
      const response = await fetch("/api/settings/github-token", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ token: githubToken }),
      });

      if (response.ok) {
        setMessage({
          type: "success",
          text: "GitHub token saved successfully!",
        });
      } else {
        const errorData = await response.json();
        setMessage({
          type: "error",
          text: errorData.error ?? "Failed to save token",
        });
      }
    } catch {
      setMessage({ type: "error", text: "Failed to save token" });
    } finally {
      setIsSaving(false);
    }
  };

  const loadColorCodingSetting = async () => {
    try {
      const response = await fetch("/api/settings/color-coding");
      if (response.ok) {
        const data = await response.json();
        setColorCodingEnabled(Boolean(data.enabled));
      }
    } catch (error) {
      console.error("Error loading color coding setting:", error);
    }
  };

  const saveColorCodingSetting = async (enabled: boolean) => {
    try {
      const response = await fetch("/api/settings/color-coding", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ enabled }),
      });

      if (response.ok) {
        setColorCodingEnabled(enabled);
        setMessage({
          type: "success",
          text: "Color coding setting saved successfully",
        });
        setTimeout(() => setMessage(null), 3000);
      } else {
        setMessage({
          type: "error",
          text: "Failed to save color coding setting",
        });
        setTimeout(() => setMessage(null), 3000);
      }
    } catch (error) {
      console.error("Error saving color coding setting:", error);
      setMessage({
        type: "error",
        text: "Failed to save color coding setting",
      });
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const loadAuthCredentials = async () => {
    setAuthLoading(true);
    try {
      const response = await fetch("/api/settings/auth-credentials");
      if (response.ok) {
        const data = (await response.json()) as {
          username: string;
          enabled: boolean;
          hasCredentials: boolean;
          setupCompleted: boolean;
        };
        setAuthUsername(data.username ?? "");
        setAuthEnabled(data.enabled ?? false);
        setAuthHasCredentials(data.hasCredentials ?? false);
        setAuthSetupCompleted(data.setupCompleted ?? false);
      }
    } catch (error) {
      console.error("Error loading auth credentials:", error);
    } finally {
      setAuthLoading(false);
    }
  };

  const saveAuthCredentials = async () => {
    if (authPassword !== authConfirmPassword) {
      setMessage({ type: "error", text: "Passwords do not match" });
      return;
    }

    setAuthLoading(true);
    setMessage(null);

    try {
      const response = await fetch("/api/settings/auth-credentials", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: authUsername,
          password: authPassword,
          enabled: authEnabled,
        }),
      });

      if (response.ok) {
        setMessage({
          type: "success",
          text: "Authentication credentials updated successfully!",
        });
        setAuthPassword("");
        setAuthConfirmPassword("");
        void loadAuthCredentials();
      } else {
        const errorData = await response.json();
        setMessage({
          type: "error",
          text: errorData.error ?? "Failed to save credentials",
        });
      }
    } catch {
      setMessage({ type: "error", text: "Failed to save credentials" });
    } finally {
      setAuthLoading(false);
    }
  };

  const toggleAuthEnabled = async (enabled: boolean) => {
    setAuthLoading(true);
    setMessage(null);

    try {
      const response = await fetch("/api/settings/auth-credentials", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ enabled }),
      });

      if (response.ok) {
        setAuthEnabled(enabled);
        setMessage({
          type: "success",
          text: `Authentication ${enabled ? "enabled" : "disabled"} successfully!`,
        });
      } else {
        const errorData = await response.json();
        setMessage({
          type: "error",
          text: errorData.error ?? "Failed to update auth status",
        });
      }
    } catch {
      setMessage({ type: "error", text: "Failed to update auth status" });
    } finally {
      setAuthLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-2 backdrop-blur-sm sm:p-4">
      <div className="bg-card max-h-[95vh] w-full max-w-4xl overflow-hidden rounded-lg shadow-xl sm:max-h-[90vh]">
        {/* Header */}
        <div className="border-border flex items-center justify-between border-b p-4 sm:p-6">
          <div className="flex items-center gap-2">
            <h2 className="text-card-foreground text-xl font-bold sm:text-2xl">
              Settings
            </h2>
            <ContextualHelpIcon
              section="general-settings"
              tooltip="Help with General Settings"
            />
          </div>
          <Button
            onClick={onClose}
            variant="ghost"
            size="icon"
            className="text-muted-foreground hover:text-foreground"
          >
            <svg
              className="h-5 w-5 sm:h-6 sm:w-6"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </Button>
        </div>

        {/* Tabs */}
        <div className="border-border border-b">
          <nav className="flex flex-col space-y-1 px-4 sm:flex-row sm:space-y-0 sm:space-x-8 sm:px-6">
            <Button
              onClick={() => setActiveTab("general")}
              variant="ghost"
              size="null"
              className={`w-full border-b-2 px-1 py-3 text-sm font-medium sm:w-auto sm:py-4 ${
                activeTab === "general"
                  ? "border-primary text-primary"
                  : "text-muted-foreground hover:text-foreground hover:border-border border-transparent"
              }`}
            >
              General
            </Button>
            <Button
              onClick={() => setActiveTab("github")}
              variant="ghost"
              size="null"
              className={`w-full border-b-2 px-1 py-3 text-sm font-medium sm:w-auto sm:py-4 ${
                activeTab === "github"
                  ? "border-primary text-primary"
                  : "text-muted-foreground hover:text-foreground hover:border-border border-transparent"
              }`}
            >
              GitHub
            </Button>
            <Button
              onClick={() => setActiveTab("auth")}
              variant="ghost"
              size="null"
              className={`w-full border-b-2 px-1 py-3 text-sm font-medium sm:w-auto sm:py-4 ${
                activeTab === "auth"
                  ? "border-primary text-primary"
                  : "text-muted-foreground hover:text-foreground hover:border-border border-transparent"
              }`}
            >
              Authentication
            </Button>
          </nav>
        </div>

        {/* Content */}
        <div className="max-h-[calc(95vh-180px)] overflow-y-auto p-4 sm:max-h-[calc(90vh-200px)] sm:p-6">
          {activeTab === "general" && (
            <div className="space-y-4 sm:space-y-6">
              <h3 className="text-foreground mb-3 text-base font-medium sm:mb-4 sm:text-lg">
                General Settings
              </h3>
              <p className="text-muted-foreground mb-4 text-sm sm:text-base">
                Configure general application preferences and behavior.
              </p>
              <div className="space-y-4">
                <div className="border-border rounded-lg border p-4">
                  <h4 className="text-foreground mb-2 font-medium">Theme</h4>
                  <p className="text-muted-foreground mb-4 text-sm">
                    Choose your preferred color theme for the application.
                  </p>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-foreground text-sm font-medium">
                        Current Theme
                      </p>
                      <p className="text-muted-foreground text-xs">
                        {theme === "light" ? "Light mode" : "Dark mode"}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        onClick={() => setTheme("light")}
                        variant={theme === "light" ? "default" : "outline"}
                        size="sm"
                      >
                        Light
                      </Button>
                      <Button
                        onClick={() => setTheme("dark")}
                        variant={theme === "dark" ? "default" : "outline"}
                        size="sm"
                      >
                        Dark
                      </Button>
                    </div>
                  </div>
                </div>

                <div className="border-border rounded-lg border p-4">
                  <h4 className="text-foreground mb-2 font-medium">
                    Save Filters
                  </h4>
                  <p className="text-muted-foreground mb-4 text-sm">
                    Save your configured script filters.
                  </p>
                  <Toggle
                    checked={saveFilter}
                    onCheckedChange={saveSaveFilter}
                    label="Enable filter saving"
                  />

                  {saveFilter && (
                    <div className="bg-muted mt-4 rounded-lg p-3">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-foreground text-sm font-medium">
                            Saved Filters
                          </p>
                          <p className="text-muted-foreground text-xs">
                            {savedFilters
                              ? "Filters are currently saved"
                              : "No filters saved yet"}
                          </p>
                          {savedFilters && (
                            <div className="text-muted-foreground mt-2 text-xs">
                              <div>
                                Search: {savedFilters.searchQuery ?? "None"}
                              </div>
                              <div>
                                Types: {savedFilters.selectedTypes?.length ?? 0}{" "}
                                selected
                              </div>
                              <div>
                                Sort: {savedFilters.sortBy} (
                                {savedFilters.sortOrder})
                              </div>
                            </div>
                          )}
                        </div>
                        {savedFilters && (
                          <Button
                            onClick={clearSavedFilters}
                            variant="outline"
                            size="sm"
                            className="text-error hover:text-error/80"
                          >
                            Clear
                          </Button>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="border-border rounded-lg border p-4">
                  <h4 className="text-foreground mb-2 font-medium">
                    Server Color Coding
                  </h4>
                  <p className="text-muted-foreground mb-4 text-sm">
                    Enable color coding for servers to visually distinguish them
                    throughout the application.
                  </p>
                  <Toggle
                    checked={colorCodingEnabled}
                    onCheckedChange={saveColorCodingSetting}
                    label="Enable server color coding"
                  />
                </div>
              </div>
            </div>
          )}

          {activeTab === "github" && (
            <div className="space-y-4 sm:space-y-6">
              <div>
                <h3 className="text-foreground mb-3 text-base font-medium sm:mb-4 sm:text-lg">
                  GitHub Integration
                </h3>
                <p className="text-muted-foreground mb-4 text-sm sm:text-base">
                  Configure GitHub integration for script management and
                  updates.
                </p>
                <div className="space-y-4">
                  <div className="border-border rounded-lg border p-4">
                    <h4 className="text-foreground mb-2 font-medium">
                      GitHub Personal Access Token
                    </h4>
                    <p className="text-muted-foreground mb-4 text-sm">
                      Save a GitHub Personal Access Token to circumvent GitHub
                      API rate limits.
                    </p>

                    <div className="space-y-3">
                      <div>
                        <label
                          htmlFor="github-token"
                          className="text-foreground mb-1 block text-sm font-medium"
                        >
                          Token
                        </label>
                        <Input
                          id="github-token"
                          type="password"
                          placeholder="Enter your GitHub Personal Access Token"
                          value={githubToken}
                          onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setGithubToken(e.target.value)
                          }
                          disabled={isLoading || isSaving}
                          className="w-full"
                        />
                      </div>

                      {message && (
                        <div
                          className={`rounded-md p-3 text-sm ${
                            message.type === "success"
                              ? "bg-success/10 text-success-foreground border-success/20 border"
                              : "bg-error/10 text-error-foreground border-error/20 border"
                          }`}
                        >
                          {message.text}
                        </div>
                      )}

                      <div className="flex gap-2">
                        <Button
                          onClick={saveGithubToken}
                          disabled={
                            isSaving || isLoading || !githubToken.trim()
                          }
                          className="flex-1"
                        >
                          {isSaving ? "Saving..." : "Save Token"}
                        </Button>
                        <Button
                          onClick={loadGithubToken}
                          disabled={isLoading || isSaving}
                          variant="outline"
                        >
                          {isLoading ? "Loading..." : "Refresh"}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === "auth" && (
            <div className="space-y-4 sm:space-y-6">
              <div>
                <h3 className="text-foreground mb-3 text-base font-medium sm:mb-4 sm:text-lg">
                  Authentication Settings
                </h3>
                <p className="text-muted-foreground mb-4 text-sm sm:text-base">
                  Configure authentication to secure access to your application.
                </p>
                <div className="space-y-4">
                  <div className="border-border rounded-lg border p-4">
                    <h4 className="text-foreground mb-2 font-medium">
                      Authentication Status
                    </h4>
                    <p className="text-muted-foreground mb-4 text-sm">
                      {authSetupCompleted
                        ? authHasCredentials
                          ? `Authentication is ${authEnabled ? "enabled" : "disabled"}. Current username: ${authUsername}`
                          : `Authentication is ${authEnabled ? "enabled" : "disabled"}. No credentials configured.`
                        : "Authentication setup has not been completed yet."}
                    </p>

                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-foreground text-sm font-medium">
                            Enable Authentication
                          </p>
                          <p className="text-muted-foreground text-xs">
                            {authEnabled
                              ? "Authentication is required on every page load"
                              : "Authentication is optional"}
                          </p>
                        </div>
                        <Toggle
                          checked={authEnabled}
                          onCheckedChange={toggleAuthEnabled}
                          disabled={authLoading || !authSetupCompleted}
                          label="Enable authentication"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="border-border rounded-lg border p-4">
                    <h4 className="text-foreground mb-2 font-medium">
                      Update Credentials
                    </h4>
                    <p className="text-muted-foreground mb-4 text-sm">
                      Change your username and password for authentication.
                    </p>

                    <div className="space-y-3">
                      <div>
                        <label
                          htmlFor="auth-username"
                          className="text-foreground mb-1 block text-sm font-medium"
                        >
                          Username
                        </label>
                        <Input
                          id="auth-username"
                          type="text"
                          placeholder="Enter username"
                          value={authUsername}
                          onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setAuthUsername(e.target.value)
                          }
                          disabled={authLoading}
                          className="w-full"
                          minLength={3}
                        />
                      </div>

                      <div>
                        <label
                          htmlFor="auth-password"
                          className="text-foreground mb-1 block text-sm font-medium"
                        >
                          New Password
                        </label>
                        <Input
                          id="auth-password"
                          type="password"
                          placeholder="Enter new password"
                          value={authPassword}
                          onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setAuthPassword(e.target.value)
                          }
                          disabled={authLoading}
                          className="w-full"
                          minLength={6}
                        />
                      </div>

                      <div>
                        <label
                          htmlFor="auth-confirm-password"
                          className="text-foreground mb-1 block text-sm font-medium"
                        >
                          Confirm Password
                        </label>
                        <Input
                          id="auth-confirm-password"
                          type="password"
                          placeholder="Confirm new password"
                          value={authConfirmPassword}
                          onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setAuthConfirmPassword(e.target.value)
                          }
                          disabled={authLoading}
                          className="w-full"
                          minLength={6}
                        />
                      </div>

                      {message && (
                        <div
                          className={`rounded-md p-3 text-sm ${
                            message.type === "success"
                              ? "bg-success/10 text-success-foreground border-success/20 border"
                              : "bg-error/10 text-error-foreground border-error/20 border"
                          }`}
                        >
                          {message.text}
                        </div>
                      )}

                      <div className="flex gap-2">
                        <Button
                          onClick={saveAuthCredentials}
                          disabled={
                            authLoading ||
                            !authUsername.trim() ||
                            !authPassword.trim() ||
                            !authConfirmPassword.trim()
                          }
                          className="flex-1"
                        >
                          {authLoading ? "Saving..." : "Update Credentials"}
                        </Button>
                        <Button
                          onClick={loadAuthCredentials}
                          disabled={authLoading}
                          variant="outline"
                        >
                          {authLoading ? "Loading..." : "Refresh"}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
