import { useTranslation } from "react-i18next";
import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useCreateApp } from "@/hooks/useCreateApp";
import { useCheckName } from "@/hooks/useCheckName";
import { useLoadConnectors } from "@/hooks/useLoadConnectors";
import { NEON_TEMPLATE_IDS, Template } from "@/shared/templates";
import { useSelectChat } from "@/hooks/useSelectChat";

import { Loader2 } from "lucide-react";
import { neonTemplateHook } from "@/client_logic/template_hook";
import { showError } from "@/lib/toast";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface CreateAppDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  template: Template | undefined;
}

export function CreateAppDialog({
  open,
  onOpenChange,
  template,
}: CreateAppDialogProps) {
  const { t } = useTranslation(["home", "common"]);
  const [appName, setAppName] = useState("");
  const [connectorValue, setConnectorValue] = useState("none");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { createApp } = useCreateApp();
  const { connectors } = useLoadConnectors();
  const { data: nameCheckResult } = useCheckName(appName);
  const { selectChat } = useSelectChat();
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!appName.trim()) {
      return;
    }

    if (nameCheckResult?.exists) {
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await createApp({
        name: appName.trim(),
        initialConnectorIds:
          connectorValue === "none" ? [] : [Number(connectorValue)],
      });
      if (template && NEON_TEMPLATE_IDS.has(template.id)) {
        await neonTemplateHook({
          appId: result.app.id,
          appName: result.app.name,
        });
      }
      // Selecting the new chat seeds recent tab order immediately.
      selectChat({ chatId: result.chatId, appId: result.app.id });
      setAppName("");
      setConnectorValue("none");
      onOpenChange(false);
    } catch (error) {
      showError(error as any);
      // Error is already handled by createApp hook or shown above
      console.error("Error creating app:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const isNameValid = appName.trim().length > 0;
  const nameExists = nameCheckResult?.exists;
  const canSubmit = isNameValid && !nameExists && !isSubmitting;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t("home:createNewApp")}</DialogTitle>
          <DialogDescription>
            {t("home:createAppUsingTemplate", { template: template?.title })}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="appName">{t("home:appName")}</Label>
              <Input
                id="appName"
                value={appName}
                onChange={(e) => setAppName(e.target.value)}
                placeholder={t("home:enterAppName")}
                className={nameExists ? "border-red-500" : ""}
                disabled={isSubmitting}
              />
              {nameExists && (
                <p className="text-sm text-red-500">
                  {t("home:appNameAlreadyExists")}
                </p>
              )}
            </div>
            {connectors.length > 0 && (
              <div className="grid gap-2">
                <Label htmlFor="appConnector">
                  {t("home:connectorOptional")}
                </Label>
                <Select
                  value={connectorValue}
                  onValueChange={(value) => setConnectorValue(value ?? "none")}
                  disabled={isSubmitting}
                >
                  <SelectTrigger id="appConnector">
                    <SelectValue
                      placeholder={t("home:selectConnectorForApp")}
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">
                      {t("home:noConnectorSelected")}
                    </SelectItem>
                    {connectors.map((connector) => (
                      <SelectItem
                        key={connector.id}
                        value={String(connector.id)}
                      >
                        {connector.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isSubmitting}
            >
              {t("common:cancel")}
            </Button>
            <Button
              type="submit"
              disabled={!canSubmit}
              className="bg-indigo-600 hover:bg-indigo-700"
            >
              {isSubmitting && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              {isSubmitting ? t("common:creating") : t("home:createApp")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
