import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { shortcutServiceClient } from "@/service";
import { useAuth } from "@/contexts/AuthContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useLoading from "@/hooks/useLoading";
import { handleError } from "@/lib/error";
import { Shortcut, ShortcutSchema } from "@/types/proto/api/v1/shortcut_service_pb";
import { useTranslate } from "@/utils/i18n";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  shortcut?: Shortcut;
  onSuccess?: () => void;
}

function CreateShortcutDialog({ open, onOpenChange, shortcut: initialShortcut, onSuccess }: Props) {
  const t = useTranslate();
  const user = useCurrentUser();
  const { refetchSettings } = useAuth();
  const [title, setTitle] = useState<string>(initialShortcut?.title || "");
  const [tag, setTag] = useState<string>("");
  const [timeRange, setTimeRange] = useState<"all" | "today" | "last7" | "last30">("all");
  const [pinnedOnly, setPinnedOnly] = useState(false);
  const [hasTaskListOnly, setHasTaskListOnly] = useState(false);
  const [hasLinkOnly, setHasLinkOnly] = useState(false);
  const [hasCodeOnly, setHasCodeOnly] = useState(false);
  const [untaggedOnly, setUntaggedOnly] = useState(false);
  const requestState = useLoading(false);
  const isCreating = !initialShortcut;

  // Reset or hydrate form state when dialog opens / shortcut changes
  useEffect(() => {
    if (!open) return;

    if (initialShortcut) {
      setTitle(initialShortcut.title || "");

      const filter = initialShortcut.filter || "";

      // Basic, best-effort parse from existing filter string
      const tagMatch = filter.match(/"([^"]+)"\s+in\s+tags/);
      setTag(tagMatch ? tagMatch[1] : "");

      setPinnedOnly(filter.includes("pinned"));
      setHasTaskListOnly(filter.includes("has_task_list"));
      setHasLinkOnly(filter.includes("has_link"));
      setHasCodeOnly(filter.includes("has_code"));
      setUntaggedOnly(filter.includes("size(tags) == 0"));

      if (filter.includes("created_ts > now() - 86400")) {
        setTimeRange("today");
      } else if (filter.includes("created_ts > now() - 604800")) {
        setTimeRange("last7");
      } else if (filter.includes("created_ts > now() - 2592000")) {
        setTimeRange("last30");
      } else {
        setTimeRange("all");
      }
    } else {
      // New shortcut: reset to defaults
      setTitle("");
      setTag("");
      setTimeRange("all");
      setPinnedOnly(false);
      setHasTaskListOnly(false);
      setHasLinkOnly(false);
      setHasCodeOnly(false);
      setUntaggedOnly(false);
    }
  }, [open, initialShortcut]);

  const buildFilter = (): string => {
    const conditions: string[] = [];

    if (tag.trim()) {
      conditions.push(`"${tag.trim()}" in tags`);
    }

    if (pinnedOnly) {
      conditions.push("pinned");
    }

    if (hasTaskListOnly) {
      conditions.push("has_task_list");
    }

    if (hasLinkOnly) {
      conditions.push("has_link");
    }

    if (hasCodeOnly) {
      conditions.push("has_code");
    }

    if (untaggedOnly) {
      conditions.push("size(tags) == 0");
    }

    if (timeRange === "today") {
      conditions.push("created_ts > now() - 86400");
    } else if (timeRange === "last7") {
      conditions.push("created_ts > now() - 604800");
    } else if (timeRange === "last30") {
      conditions.push("created_ts > now() - 2592000");
    }

    return conditions.join(" && ");
  };

  const handleSaveBtnClick = async () => {
    if (!title.trim()) {
      toast.error("Title cannot be empty");
      return;
    }

    const filter = buildFilter();

    try {
      requestState.setLoading();
      if (isCreating) {
        await shortcutServiceClient.createShortcut({
          parent: user?.name,
          shortcut: {
            name: "",
            title: title.trim(),
            filter,
          },
        });
        toast.success("Create workspace successfully");
      } else {
        await shortcutServiceClient.updateShortcut({
          shortcut: {
            ...create(ShortcutSchema, {
            name: initialShortcut!.name,
              title: title.trim(),
              filter,
            }),
          },
          updateMask: create(FieldMaskSchema, { paths: ["title", "filter"] }),
        });
        toast.success("Update workspace successfully");
      }
      await refetchSettings();
      requestState.setFinish();
      onSuccess?.();
      onOpenChange(false);
    } catch (error: unknown) {
      await handleError(error, toast.error, {
        context: isCreating ? "Create workspace" : "Update workspace",
        onError: () => requestState.setError(),
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{`${isCreating ? t("common.create") : t("common.edit")} ${t("common.shortcuts")}`}</DialogTitle>
        </DialogHeader>
        <div className="flex flex-col gap-4">
          <div className="grid gap-2">
            <Label htmlFor="title">{t("common.title")}</Label>
            <Input id="title" type="text" placeholder="" value={title} onChange={(e) => setTitle(e.target.value)} />
          </div>
          <div className="grid gap-2">
            <Label className="text-sm font-medium">Điều kiện (chọn, không cần gõ cú pháp)</Label>
            <div className="space-y-3 rounded-md border bg-muted/40 p-3">
              <div className="grid gap-2">
                <Label htmlFor="shortcut-tag" className="text-xs text-muted-foreground">
                  Tag (tùy chọn)
                </Label>
                <Input
                  id="shortcut-tag"
                  type="text"
                  placeholder='Ví dụ: work, kafka'
                  value={tag}
                  onChange={(e) => setTag(e.target.value)}
                />
              </div>
              <div className="grid gap-2">
                <Label className="text-xs text-muted-foreground">Thời gian</Label>
                <select
                  className="h-9 rounded-md border border-input bg-background px-2 text-sm"
                  value={timeRange}
                  onChange={(e) => setTimeRange(e.target.value as typeof timeRange)}
                >
                  <option value="all">Tất cả thời gian</option>
                  <option value="today">Hôm nay</option>
                  <option value="last7">7 ngày gần đây</option>
                  <option value="last30">30 ngày gần đây</option>
                </select>
              </div>
              <div className="grid gap-2">
                <Label className="text-xs text-muted-foreground">Lọc theo loại nội dung</Label>
                <div className="flex flex-col gap-2 text-sm text-foreground">
                  <label className="flex items-center gap-2">
                    <Checkbox checked={pinnedOnly} onCheckedChange={(v) => setPinnedOnly(Boolean(v))} />
                    <span>Chỉ ghi chú được ghim</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <Checkbox checked={hasTaskListOnly} onCheckedChange={(v) => setHasTaskListOnly(Boolean(v))} />
                    <span>Có checklist (task list)</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <Checkbox checked={hasLinkOnly} onCheckedChange={(v) => setHasLinkOnly(Boolean(v))} />
                    <span>Có liên kết</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <Checkbox checked={hasCodeOnly} onCheckedChange={(v) => setHasCodeOnly(Boolean(v))} />
                    <span>Có code block</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <Checkbox checked={untaggedOnly} onCheckedChange={(v) => setUntaggedOnly(Boolean(v))} />
                    <span>Chưa có tag (ghi chú nháp)</span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="ghost" disabled={requestState.isLoading} onClick={() => onOpenChange(false)}>
            {t("common.cancel")}
          </Button>
          <Button disabled={requestState.isLoading} onClick={handleSaveBtnClick}>
            {t("common.save")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default CreateShortcutDialog;
