import { useState, type ReactNode } from "react";
import { Hash, Loader2 } from "lucide-react";

import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

import type {
  FileUploadEntity,
  FileUploadSetting,
} from "@/types/fileUploadSettings";
import {
  useCreateFileUploadSetting,
  useUpdateFileUploadSetting,
} from "@/hooks/useFileUploadSettings";

export interface EditFileUploadSettingDialogProps {
  mode?: "create" | "edit";
  setting?: FileUploadSetting;
  children: ReactNode;
}

const selectClass =
  "flex h-10 w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 shadow-xs outline-none transition hover:border-slate-300 focus:border-[#10B981]/50 focus:ring-2 focus:ring-[#10B981]/20";

const ENTITIES: FileUploadEntity[] = [
  "customer",
  "booking",
  "consignment",
  "shipment",
  "invoice",
  "train",
  "other",
];

export default function EditFileUploadSettingDialog({
  mode = "create",
  setting,
  children,
}: EditFileUploadSettingDialogProps) {
  const isEdit = mode === "edit";

  const [open, setOpen] = useState(false);
  const [code, setCode] = useState(setting?.code ?? "");
  const [label, setLabel] = useState(setting?.label ?? "");
  const [entity, setEntity] = useState<FileUploadEntity>(
    setting?.entity ?? "other",
  );
  const [description, setDescription] = useState(setting?.description ?? "");
  const [error, setError] = useState<string | null>(null);

  const createMutation = useCreateFileUploadSetting();
  const updateMutation = useUpdateFileUploadSetting();
  const pending = createMutation.isPending || updateMutation.isPending;

  const reset = () => {
    setCode(setting?.code ?? "");
    setLabel(setting?.label ?? "");
    setEntity(setting?.entity ?? "other");
    setDescription(setting?.description ?? "");
    setError(null);
  };

  const handleSubmit = () => {
    setError(null);
    if (!code.trim() || !label.trim()) {
      setError("Code and label are required.");
      return;
    }

    const payload = {
      code: code.trim(),
      label: label.trim(),
      entity,
      description: description.trim() || undefined,
    };

    const onDone = () => {
      setOpen(false);
      if (!isEdit) reset();
    };
    const onError = (err: unknown) => {
      setError(
        err instanceof Error ? err.message : "Something went wrong. Try again.",
      );
    };

    if (isEdit && setting) {
      updateMutation.mutate(
        { id: setting.id, dto: payload },
        { onSuccess: onDone, onError },
      );
    } else {
      createMutation.mutate(payload, { onSuccess: onDone, onError });
    }
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        setOpen(next);
        if (!next) reset();
      }}
    >
      <DialogTrigger asChild>{children}</DialogTrigger>

      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl rounded-3xl">
        <DialogHeader>
          <DialogTitle className="text-2xl font-bold">
            {isEdit ? "Edit File Upload Setting" : "New File Upload Setting"}
          </DialogTitle>
          <DialogDescription>
            {isEdit
              ? "Update the metadata for this file upload group."
              : "Define a new file upload group that a form can reference by code."}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-5 py-4 md:grid-cols-2">
          <div className="space-y-2">
            <Label>Code *</Label>
            <div className="relative">
              <Hash className="absolute left-3 top-3 h-4 w-4 text-slate-400" />
              <Input
                value={code}
                onChange={(e) => setCode(e.target.value)}
                placeholder="e.g. customer_registration"
                className="pl-10 font-mono"
                disabled={isEdit}
              />
            </div>
            <p className="text-xs text-slate-500">
              {isEdit
                ? "Code is immutable after creation."
                : "Stable identifier used in code. Use snake_case."}
            </p>
          </div>

          <div className="space-y-2">
            <Label>Label *</Label>
            <Input
              value={label}
              onChange={(e) => setLabel(e.target.value)}
              placeholder="e.g. Customer Registration"
            />
          </div>

          <div className="space-y-2">
            <Label>Entity</Label>
            <select
              value={entity}
              onChange={(e) => setEntity(e.target.value as FileUploadEntity)}
              className={selectClass}
            >
              {ENTITIES.map((e) => (
                <option key={e} value={e} className="capitalize">
                  {e[0]!.toUpperCase() + e.slice(1)}
                </option>
              ))}
            </select>
            <p className="text-xs text-slate-500">
              Domain the upload group applies to.
            </p>
          </div>

          <div className="space-y-2">
            <Label>Field Count</Label>
            <Input
              disabled
              value={String(setting?.fields.length ?? 0)}
              className="bg-slate-50 text-slate-600"
            />
            <p className="text-xs text-slate-500">
              Manage fields from the "Fields" action on the list.
            </p>
          </div>

          <div className="space-y-2 md:col-span-2">
            <Label>Description</Label>
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="What this upload group represents and where it's used..."
            />
          </div>
        </div>

        {error ? (
          <p className="rounded-xl bg-red-50 px-3 py-2 text-sm text-red-700">
            {error}
          </p>
        ) : null}

        <div className="mt-2 flex justify-end gap-3">
          <DialogClose asChild>
            <Button variant="outline" disabled={pending}>
              Cancel
            </Button>
          </DialogClose>
          <Button
            type="button"
            onClick={handleSubmit}
            disabled={pending}
            className="bg-[#10B981] text-white hover:bg-[#10B981]/90 disabled:opacity-60"
          >
            {pending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : isEdit ? (
              "Save Changes"
            ) : (
              "Create Setting"
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
