import React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import { toast } from "sonner";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { MultiSelect } from "@/shared/common/ui/multi-select";
import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import { useTranslation } from "react-i18next";

interface ActionConfig {
  type:
    | "accept"
    | "delete"
    | "submit"
    | "custom"
    | "adjust"
    | "forward"
    | "assigne"
    | "reject"
    | "download";
  confirmText?: string;
  confirmVariant?:
    | "default"
    | "destructive"
    | "outline"
    | "secondary"
    | "ghost"
    | "link";
  isLoading?: boolean;
  disabled?: boolean;
  onAction: (data?: Record<string, any>) => Promise<void> | void;
}

interface FormFieldConfig {
  name: string;
  label: string;
  type: "text" | "textarea" | "select" | "checkbox" | "multiselect";
  placeholder?: string;
  options?: {
    value: string;
    label: string;
    icon?: React.ComponentType<{ className?: string }>;
  }[];
  defaultValue?: any;
  required?: boolean;
  rules?: Record<string, any>;
  variant?: "default" | "secondary" | "destructive" | "inverted";
  animation?: number;
  maxCount?: number;
}

interface DynamicModalProps {
  open: boolean;
  onClose: () => void;
  title: string;
  description?: string;
  actionConfig: ActionConfig;
  formConfig?: {
    fields: FormFieldConfig[];
    onSubmit?: (data: Record<string, any>) => void | Promise<void>;
    defaultValues?: Record<string, any>;
  };
  customContent?: React.ReactNode;
}

// 👇 Loader Component
const Loader = () => (
  <svg
    className="animate-spin h-4 w-4 text-white"
    xmlns="http://www.w3.org/2000/svg"
    fill="none"
    viewBox="0 0 24 24"
  >
    <circle
      className="opacity-25"
      cx="12"
      cy="12"
      r="10"
      stroke="currentColor"
      strokeWidth="4"
    ></circle>
    <path
      className="opacity-75"
      fill="currentColor"
      d="M4 12a8 8 0 018-8v8H4z"
    ></path>
  </svg>
);

const EnhancedDynamicModal: React.FC<DynamicModalProps> = ({
  open,
  onClose,
  title,
  description,
  actionConfig,
  formConfig,
  customContent,
}) => {
  const form = useForm({
    defaultValues: formConfig?.defaultValues || {},
  });

  const [loading, setLoading] = React.useState(false);
  const [formData, setFormData] = React.useState<Record<string, any>>({});
  const { t } = useTranslation();

  const handleSubmit = async (data: Record<string, any>) => {
    try {
      setLoading(true);
      if (formConfig?.onSubmit) {
        await formConfig.onSubmit(data);
      }
      await actionConfig.onAction(data);
      onClose();
    } catch (error) {
      console.error("Modal submission error:", error);
      toast.error(
        "Action failed: " +
          (error instanceof Error ? error.message : String(error)),
      );
    } finally {
      setLoading(false);
    }
  };

  const handleActionClick = async () => {
    try {
      setLoading(true);
      await actionConfig.onAction();
      onClose();
    } catch (error) {
      console.error("Action failed:", error);
      toast.error(
        "Action failed: " +
          (error instanceof Error ? error.message : String(error)),
      );
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => {
    const { name, value, type } = e.target;
    const checked =
      type === "checkbox" ? (e.target as HTMLInputElement).checked : undefined;

    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  const getActionButtonText = () => {
    if (actionConfig.confirmText) return actionConfig.confirmText;
    switch (actionConfig.type) {
      case "accept":
        return "Accept";
      case "delete":
        return "Delete";
      case "submit":
        return "Submit";
      case "adjust":
        return "Adjust";
      case "forward":
        return "Forward";
      case "reject":
        return "Reject";
      default:
        return "Confirm";
    }
  };

  const getActionButtonVariant = () => {
    if (actionConfig.confirmVariant) return actionConfig.confirmVariant;
    switch (actionConfig.type) {
      case "delete":
        return "destructive";
      default:
        return "default";
    }
  };

  const renderFormField = (field: FormFieldConfig) => {
    switch (field.type) {
      case "multiselect":
        return (
          <FormField
            control={form.control}
            name={field.name}
            rules={field.rules}
            render={({ field: formField }) => (
              <FormItem className="space-y-1">
                <FormLabel>{field.label}</FormLabel>
                <FormControl>
                  <MultiSelect
                    options={field.options || []}
                    onValueChange={(value: string[]) => {
                      formField.onChange(value);
                    }}
                    defaultValue={formField.value}
                    placeholder={field.placeholder}
                    variant={field.variant || "default"}
                    animation={field.animation || 0}
                    maxCount={field.maxCount || 3}
                    className="z-[60]"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        );
      case "select":
        return (
          <FormField
            control={form.control}
            name={field.name}
            render={({ field: formField }) => (
              <FormItem>
                <FormLabel>{field.label}</FormLabel>
                <Select
                  onValueChange={formField.onChange}
                  value={formField.value}
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder={field.placeholder} />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent className="z-[80]">
                    {field.options?.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FormMessage />
              </FormItem>
            )}
          />
        );
      case "text":
        return (
          <FormField
            key={field.name}
            control={form.control}
            name={field.name}
            render={({ field: formField }) => (
              <FormItem>
                <FormLabel>{field.label}</FormLabel>
                <FormControl>
                  <input
                    {...formField}
                    type="text"
                    placeholder={field.placeholder}
                    className="w-full px-3 py-2 border rounded"
                    required={field.required}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        );

      case "textarea":
        return (
          <FormField
            key={field.name}
            control={form.control}
            name={field.name}
            render={({ field: formField }) => (
              <FormItem className="w-full">
                <FormLabel>{field.label}</FormLabel>
                <FormControl>
                  <textarea
                    {...formField}
                    placeholder={field.placeholder}
                    className="w-full px-3 py-2 border rounded resize-none break-words overflow-wrap-anywhere whitespace-pre-wrap"
                    style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}
                    rows={4}
                    required={field.required}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        );

      case "checkbox":
        return (
          <div className="mb-4 flex items-center" key={field.name}>
            <input
              type="checkbox"
              id={field.name}
              name={field.name}
              checked={!!formData[field.name]}
              onChange={handleChange}
              className="mr-2 bg-primary-800"
              required={field.required}
            />
            <label htmlFor={field.name} className="text-sm font-medium">
              {field.label}
            </label>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          {description && (
            <p className="text-sm text-muted-foreground">{description}</p>
          )}
        </DialogHeader>

        {customContent}

        {formConfig ? (
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(handleSubmit)}
              className="space-y-4 w-full"
            >
              <div className="w-full space-y-4">
              {formConfig.fields.map((field) => (
                <React.Fragment key={field.name}>
                  {renderFormField(field)}
                </React.Fragment>
              ))}
              </div>

              <DialogFooter>
                <Button variant="outline" onClick={onClose} disabled={loading}>
                  {t("common.Cancel")}
                </Button>
                <Button
                  type="submit"
                  variant={getActionButtonVariant()}
                  disabled={loading}
                  className=" bg-primary-800"
                >
                  {loading ? <Loader /> : getActionButtonText()}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        ) : (
          <>
            {customContent}
            <DialogFooter>
              <Button variant="outline" onClick={onClose} disabled={loading}>
                {t("common.Cancel")}
              </Button>
              <Button
                onClick={handleActionClick}
                variant={getActionButtonVariant()}
                disabled={loading}
                className=" bg-primary-800"
              >
                {loading ? <Loader /> : getActionButtonText()}
              </Button>
            </DialogFooter>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default EnhancedDynamicModal;
