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";
import { useTagCounts } from "@/hooks/useUserQueries";

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 { data: tagCounts } = useTagCounts(true);
  const [title, setTitle] = useState<string>(initialShortcut?.title || "");
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [tagSearch, setTagSearch] = useState("");
  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 [contentSearch, setContentSearch] = useState("");
  const requestState = useLoading(false);
  const isCreating = !initialShortcut;

  // Get all available tags sorted by count (descending)
  const allTags = tagCounts
    ? Object.entries(tagCounts)
      .sort(([, a], [, b]) => b - a)
      .map(([tag]) => tag)
    : [];

  // Filter tags based on search input
  const filteredTags = tagSearch.trim()
    ? allTags.filter((tag) => tag.toLowerCase().includes(tagSearch.toLowerCase()))
    : allTags;

  const toggleTag = (tag: string) => {
    setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]));
  };

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

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

      const filter = initialShortcut.filter || "";

      // Parse multiple tags from filter string
      // Format: "tag1" in tags && "tag2" in tags
      const tagMatches = filter.matchAll(/"([^"]+)"\s+in\s+tags/g);
      const parsedTags: string[] = [];
      for (const match of tagMatches) {
        parsedTags.push(match[1]);
      }
      setSelectedTags(parsedTags);

      // Parse content search
      const contentMatch = filter.match(/content\.contains\("([^"]+)"\)/);
      setContentSearch(contentMatch ? contentMatch[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("");
      setSelectedTags([]);
      setTagSearch("");
      setTimeRange("all");
      setPinnedOnly(false);
      setHasTaskListOnly(false);
      setHasLinkOnly(false);
      setHasCodeOnly(false);
      setUntaggedOnly(false);
      setContentSearch("");
    }
  }, [open, initialShortcut]);

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

    // Multiple tags support
    for (const tag of selectedTags) {
      conditions.push(`"${tag}" in tags`);
    }

    if (contentSearch.trim()) {
      conditions.push(`content.contains("${contentSearch.trim()}")`);
    }

    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("Tạo workspace thành công! 🎉");
      } else {
        await shortcutServiceClient.updateShortcut({
          shortcut: {
            ...create(ShortcutSchema, {
              name: initialShortcut!.name,
              title: title.trim(),
              filter,
            }),
          },
          updateMask: create(FieldMaskSchema, { paths: ["title", "filter"] }),
        });
        toast.success("Cập nhật workspace thành công! ✅");
      }
      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-lg max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{`${isCreating ? t("common.create") : t("common.edit")} Workspace`}</DialogTitle>
        </DialogHeader>
        <div className="flex flex-col gap-4">
          {/* Title */}
          <div className="grid gap-2">
            <Label htmlFor="title">{t("common.title")}</Label>
            <Input
              id="title"
              type="text"
              placeholder="VD: 📋 Công việc, 🔥 Quan trọng..."
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </div>

          {/* Filter conditions */}
          <div className="grid gap-2">
            <Label className="text-sm font-medium">Điều kiện lọc</Label>
            <div className="space-y-4 rounded-md border bg-muted/40 p-3">

              {/* Multi-tag selector */}
              <div className="grid gap-2">
                <Label className="text-xs text-muted-foreground">
                  🏷️ Chọn Tags ({selectedTags.length > 0 ? `đã chọn ${selectedTags.length}` : "chưa chọn"})
                </Label>

                {/* Selected tags display */}
                {selectedTags.length > 0 && (
                  <div className="flex flex-wrap gap-1.5 mb-1">
                    {selectedTags.map((tag) => (
                      <button
                        key={tag}
                        type="button"
                        onClick={() => toggleTag(tag)}
                        className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/80 transition-colors"
                      >
                        #{tag}
                        <span className="ml-0.5 text-[10px] opacity-70">✕</span>
                      </button>
                    ))}
                  </div>
                )}

                {/* Search filter for tags */}
                {allTags.length > 5 && (
                  <Input
                    type="text"
                    placeholder="🔍 Tìm tag..."
                    value={tagSearch}
                    onChange={(e) => setTagSearch(e.target.value)}
                    className="h-8 text-xs"
                  />
                )}

                {/* Available tags grid */}
                {allTags.length > 0 ? (
                  <div className="flex flex-wrap gap-1.5 max-h-32 overflow-y-auto rounded-md border bg-background p-2">
                    {filteredTags.map((tag) => {
                      const isSelected = selectedTags.includes(tag);
                      const count = tagCounts?.[tag] || 0;
                      return (
                        <button
                          key={tag}
                          type="button"
                          onClick={() => toggleTag(tag)}
                          className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-all cursor-pointer ${isSelected
                              ? "bg-primary text-primary-foreground border-primary shadow-sm"
                              : "bg-muted/50 text-muted-foreground border-border hover:border-primary/50 hover:bg-muted"
                            }`}
                        >
                          <span className="opacity-60">#</span>
                          {tag}
                          <span className="text-[10px] opacity-50">({count})</span>
                        </button>
                      );
                    })}
                    {filteredTags.length === 0 && tagSearch && (
                      <span className="text-xs text-muted-foreground italic p-1">Không tìm thấy tag &quot;{tagSearch}&quot;</span>
                    )}
                  </div>
                ) : (
                  <div className="text-xs text-muted-foreground italic p-2 border rounded-md bg-background">
                    Chưa có tag nào. Hãy thêm #tag vào ghi chú trước.
                  </div>
                )}
              </div>

              {/* Content search */}
              <div className="grid gap-2">
                <Label className="text-xs text-muted-foreground">
                  🔍 Tìm theo nội dung (tùy chọn)
                </Label>
                <Input
                  type="text"
                  placeholder="VD: docker, kubernetes..."
                  value={contentSearch}
                  onChange={(e) => setContentSearch(e.target.value)}
                  className="h-8 text-sm"
                />
              </div>

              {/* Time range */}
              <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>

              {/* Content type filters */}
              <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;
