import React, { lazy, Suspense } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "../../../../../../src/components/ui/dialog";
import { Button } from "../../../../../../src/components/ui/button";
import { Input } from "../../../../../../src/components/ui/input";
import { Label } from "../../../../../../src/components/ui/label";
import { Switch } from "../../../../../../src/components/ui/switch";
import { Upload, X, Image } from "lucide-react";

const Editor = lazy(
  () => import("../../../../../../src/app/admin/_components/editor/Editor"),
);

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingCategory: any;
  formData: any;
  setFormData: React.Dispatch<React.SetStateAction<any>>;
  imageFile: File | null;
  setImageFile: React.Dispatch<React.SetStateAction<File | null>>;
  handleSubmit: (e: React.FormEvent) => void;
  loading: boolean;
  resetForm: () => void;
  isValidCategoryName: (name: string) => boolean;
  toast: any;
}

const CategoryFormDialog = ({
  open,
  onOpenChange,
  editingCategory,
  formData,
  setFormData,
  imageFile,
  setImageFile,
  handleSubmit,
  loading,
  resetForm,
  isValidCategoryName,
  toast,
}: Props) => {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
          <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
            <DialogHeader>
              <DialogTitle>
                {editingCategory ? "Edit Category" : "Add New Category"}
              </DialogTitle>
              <X
                className="h-6 w-6 cursor-pointer p-1 text-white"
                onClick={() => {
                  onOpenChange(false);
                  resetForm();
                }}
              />
            </DialogHeader>

            <form
              onSubmit={handleSubmit}
              className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2"
            >
              <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                {/* NAME */}
                <div>
                  <Label className="mb-2 block" htmlFor="name">
                    Category Name <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => {
                      const value = e.target.value;
                      if (/^[A-Za-z\s]*$/.test(value) || value === "") {
                        setFormData((prev: any) => ({ ...prev, name: value }));
                      }
                    }}
                    onBlur={(e) => {
                      const trimmed = e.target.value.trim();
                      if (trimmed && !isValidCategoryName(trimmed)) {
                        toast.error(
                          "Category name can only contain letters and spaces (no numbers or special characters)",
                        );
                      }
                    }}
                    placeholder="e.g., Electronics, Clothing, Books"
                    required
                  />
                </div>

                {/* IMAGE */}
                <div className="space-y-2">
                  <Label className="mb-1 block" htmlFor="image">
                    Category Image
                  </Label>
                  <div className="flex items-center gap-3">
                    {formData.image ? (
                      <div className="group relative flex-shrink-0">
                        <img
                          src={formData.image}
                          alt="Preview"
                          className="h-12 w-12 rounded-md border border-gray-200 object-cover"
                        />
                        <button
                          type="button"
                          onClick={() => {
                            setFormData((prev: any) => ({
                              ...prev,
                              image: "",
                            }));
                            setImageFile(null);
                          }}
                          className="absolute -right-1.5 -top-1.5 rounded-full bg-red-500 p-0.5 text-white opacity-0 transition-opacity group-hover:opacity-100"
                        >
                          <X className="h-2.5 w-2.5" />
                        </button>
                      </div>
                    ) : (
                      <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-md border border-gray-200 bg-gray-100">
                        <Image className="h-5 w-5 text-gray-400" />
                      </div>
                    )}

                    <div className="flex-1">
                      <label className="flex cursor-pointer items-center justify-center rounded-md border border-gray-200 bg-gray-50 px-3 py-2 transition-colors hover:bg-gray-100">
                        <Upload className="mr-1.5 h-3.5 w-3.5 text-gray-500" />
                        <span className="text-xs text-gray-600">
                          {formData.image ? "Change" : "Upload"}
                        </span>
                        <Input
                          id="image"
                          type="file"
                          accept="image/*"
                          className="hidden"
                          onChange={(e) => {
                            const file = e.target.files?.[0];
                            if (file) {
                              if (file.size > 2 * 1024 * 1024) {
                                toast.error("File size must be less than 2MB");
                                return;
                              }
                              setImageFile(file);
                              const previewUrl = URL.createObjectURL(file);
                              setFormData((prev: any) => ({
                                ...prev,
                                image: previewUrl,
                              }));
                            }
                          }}
                        />
                      </label>
                      <p className="mt-1 text-xs text-gray-400">Max 2MB</p>
                    </div>
                  </div>
                </div>

                {/* DESCRIPTION */}
                <div>
                  <Label htmlFor="description">Description</Label>
                  <Suspense
                    fallback={
                      <div className="h-32 animate-pulse rounded-md border bg-gray-100" />
                    }
                  >
                    <Editor
                      value={formData.description}
                      onChange={(value: any) =>
                        setFormData((prev: any) => ({
                          ...prev,
                          description: value,
                        }))
                      }
                    />
                  </Suspense>
                </div>

                {/* STATUS */}
                <div className="flex items-center gap-2">
                  <Switch
                    checked={formData.isActive}
                    onCheckedChange={(checked) =>
                      setFormData((prev: any) => ({
                        ...prev,
                        isActive: checked,
                      }))
                    }
                    className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                  />
                  <Label>{formData.isActive ? "Active" : "Inactive"}</Label>
                </div>

                {/* EVENT TYPE */}
                <div className="flex items-center gap-2">
                  <Switch
                    checked={formData.isEvent}
                    onCheckedChange={(checked) =>
                      setFormData((prev: any) => ({
                        ...prev,
                        isEvent: checked,
                      }))
                    }
                    className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                  />
                  <Label>
                    {formData.isEvent ? "Event Category" : "Regular Category"}
                  </Label>
                </div>
              </div>

              {/* FOOTER */}
              <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    onOpenChange(false);
                    resetForm();
                  }}
                >
                  Cancel
                </Button>
                <Button type="submit">
                  {editingCategory
                    ? loading
                      ? "Updating..."
                      : "Update"
                    : loading
                      ? "Creating..."
                      : "Create"}
                </Button>
              </div>
            </form>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default React.memo(CategoryFormDialog);
