"use client";

import { useEffect, useState, type FormEvent } from "react";
import { buildCategoryIconDetails, DynamicLucideIcon } from "@/components/lucide-icon";
import {
  CATEGORY_COLOR_OPTIONS,
  CATEGORY_ICON_NAMES,
  DEFAULT_CATEGORY_COLOR,
  DEFAULT_CATEGORY_ICON,
  type CategoryIconName,
} from "@/features/categories/constants/category-appearance";
import { categoriesDict } from "@/features/categories/dict";
import type { CategoryDetails } from "@/types/category";

export type CategoryCreateModalValues = {
  label: string;
  iconComponent: CategoryIconName;
  color: string;
  details: CategoryDetails;
};

type CategoryCreateModalProps = {
  open: boolean;
  isSubmitting?: boolean;
  onClose: () => void;
  onSubmit: (values: CategoryCreateModalValues) => void;
};

export function CategoryCreateModal({
  open,
  isSubmitting = false,
  onClose,
  onSubmit,
}: CategoryCreateModalProps) {
  const [label, setLabel] = useState("");
  const [iconComponent, setIconComponent] =
    useState<CategoryIconName>(DEFAULT_CATEGORY_ICON);
  const [color, setColor] = useState<string>(DEFAULT_CATEGORY_COLOR);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) {
      return;
    }

    setLabel("");
    setIconComponent(DEFAULT_CATEGORY_ICON);
    setColor(DEFAULT_CATEGORY_COLOR);
    setError(null);
  }, [open]);

  useEffect(() => {
    if (!open) {
      return;
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape" && !isSubmitting) {
        onClose();
      }
    };

    document.addEventListener("keydown", handleEscape);
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", handleEscape);
      document.body.style.overflow = "";
    };
  }, [open, isSubmitting, onClose]);

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const trimmedLabel = label.trim();
    if (!trimmedLabel) {
      setError(categoriesDict.labelRequired);
      return;
    }

    setError(null);
    onSubmit({
      label: trimmedLabel,
      iconComponent,
      color,
      details: buildCategoryIconDetails(iconComponent, color),
    });
  };

  if (!open) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-[120] flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4">
      <button
        type="button"
        aria-label={categoriesDict.cancel}
        className="absolute inset-0"
        onClick={() => {
          if (!isSubmitting) {
            onClose();
          }
        }}
      />

      <div className="relative z-10 flex max-h-[92vh] w-full max-w-lg flex-col overflow-hidden rounded-t-3xl bg-card shadow-soft sm:rounded-3xl">
        <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col">
          <div className="border-b border-border px-6 py-4">
            <h2 className="text-lg font-bold text-card-foreground">
              {categoriesDict.createModalTitle}
            </h2>
          </div>

          <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
            <div className="space-y-2">
              <label
                htmlFor="category-label"
                className="text-sm font-medium text-card-foreground"
              >
                {categoriesDict.label}
              </label>
              <input
                id="category-label"
                value={label}
                onChange={(event) => {
                  setLabel(event.target.value);
                  if (error) {
                    setError(null);
                  }
                }}
                placeholder={categoriesDict.newCategoryPlaceholder}
                className="h-12 w-full rounded-2xl bg-input px-4 text-sm shadow-soft-sm ring-1 ring-border outline-none focus:ring-2 focus:ring-primary"
              />
              {error ? (
                <p className="text-sm text-destructive">{error}</p>
              ) : null}
            </div>

            <div className="space-y-3">
              <p className="text-sm font-medium text-card-foreground">
                {categoriesDict.iconLabel}
              </p>
              <div className="grid max-h-48 grid-cols-6 gap-2 overflow-y-auto rounded-2xl bg-input p-3 ring-1 ring-border sm:grid-cols-7">
                {CATEGORY_ICON_NAMES.map((name) => {
                  const selected = iconComponent === name;

                  return (
                    <button
                      key={name}
                      type="button"
                      aria-label={name}
                      aria-pressed={selected}
                      onClick={() => setIconComponent(name)}
                      className={`inline-flex aspect-square items-center justify-center rounded-xl transition-colors ${
                        selected
                          ? "bg-primary text-primary-foreground ring-2 ring-primary"
                          : "bg-card text-foreground hover:bg-accent"
                      }`}
                      style={selected ? undefined : { color }}
                    >
                      <DynamicLucideIcon
                        iconComponent={name}
                        size={18}
                        color={selected ? undefined : color}
                      />
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="space-y-3">
              <p className="text-sm font-medium text-card-foreground">
                {categoriesDict.colorLabel}
              </p>
              <div className="flex flex-wrap gap-2">
                {CATEGORY_COLOR_OPTIONS.map((optionColor) => {
                  const selected = color === optionColor;

                  return (
                    <button
                      key={optionColor}
                      type="button"
                      aria-label={optionColor}
                      aria-pressed={selected}
                      onClick={() => setColor(optionColor)}
                      className={`inline-flex size-10 items-center justify-center rounded-full transition-transform ${
                        selected ? "scale-110 ring-2 ring-primary ring-offset-2" : ""
                      }`}
                      style={{ backgroundColor: optionColor }}
                    />
                  );
                })}
              </div>
            </div>

            <div className="rounded-2xl bg-muted/40 p-4">
              <p className="mb-3 text-xs text-muted-foreground">پیش‌نمایش</p>
              <div className="flex items-center gap-3">
                <span
                  className="inline-flex size-10 items-center justify-center rounded-xl bg-card"
                  style={{ color }}
                >
                  <DynamicLucideIcon iconComponent={iconComponent} color={color} size={20} />
                </span>
                <span className="text-sm font-medium text-card-foreground">
                  {label.trim() || categoriesDict.newCategoryPlaceholder}
                </span>
              </div>
            </div>
          </div>

          <div className="flex flex-row gap-3 border-t border-border px-6 py-4">
            <button
              type="submit"
              disabled={isSubmitting}
              className="inline-flex h-12 flex-1 items-center justify-center rounded-2xl bg-primary px-4 text-sm font-semibold text-primary-foreground shadow-soft-sm disabled:opacity-60"
            >
              {categoriesDict.createCategory}
            </button>
            <button
              type="button"
              disabled={isSubmitting}
              onClick={onClose}
              className="inline-flex h-12 flex-1 items-center justify-center rounded-2xl bg-muted px-4 text-sm font-semibold text-foreground disabled:opacity-60"
            >
              {categoriesDict.cancel}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
