import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { SiteDto, SitePayloadDto } from "@/super-admin/dto/SitesDto";
import { toSnakeCase } from "@/super-admin/hooks/useSites";

interface SiteFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (payload: SitePayloadDto) => void;
  site?: SiteDto | null; // If provided, we are in Edit mode
  isSubmitting: boolean;
  existingKeys: string[]; // for frontend uniqueness check
}

export default function SiteFormModal({
  isOpen,
  onClose,
  onSubmit,
  site = null,
  isSubmitting,
  existingKeys,
}: SiteFormModalProps) {
  const { t } = useTranslation();
  const isEdit = !!site;
  
  const [nameAm, setNameAm] = useState("");
  const [nameEn, setNameEn] = useState("");
  const [key, setKey] = useState("");
  const [domain, setDomain] = useState("");
  
  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    if (isOpen) {
      if (site) {
        setNameAm(site.name?.am || "");
        setNameEn(site.name?.en || "");
        setKey(site.key || "");
        setDomain(site.domain || "");
      } else {
        setNameAm("");
        setNameEn("");
        setKey("");
        setDomain("");
      }
      setErrors({});
    }
  }, [isOpen, site]);

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!nameAm.trim()) {
      newErrors.nameAm = t("sites.form.nameAmRequired");
    }
    if (!nameEn.trim()) {
      newErrors.nameEn = t("sites.form.nameEnRequired");
    }
    
    if (!key.trim()) {
      newErrors.key = t("sites.form.keyRequired");
    } else if (!/^[a-zA-Z0-9_-]+$/.test(key)) {
      newErrors.key = t("sites.form.keyFormat");
    } else if (!isEdit && existingKeys.includes(key.trim())) {
      newErrors.key = t("sites.form.keyUnique");
    }

    if (!domain.trim()) {
      newErrors.domain = t("sites.form.domainRequired");
    } else if (/\s/.test(domain)) {
      newErrors.domain = t("sites.form.domainNoSpaces");
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    onSubmit({
      name: {
        am: nameAm.trim(),
        en: nameEn.trim(), // transformed to snake_case in the hook/mutation
      },
      key: key.trim(),
      domain: domain.trim(),
    });
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="text-xl font-bold text-slate-800 dark:text-slate-100">
            {isEdit ? t("sites.form.titleEdit") : t("sites.form.titleAdd")}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-5 py-2">
          {/* Site Name (Amharic) */}
          <div className="space-y-1">
            <Label htmlFor="nameAm" className="text-sm font-semibold">
              {t("sites.form.nameAmLabel")} <span className="text-red-500">*</span>
            </Label>
            <Input
              id="nameAm"
              value={nameAm}
              onChange={(e) => setNameAm(e.target.value)}
               placeholder={t("sites.form.nameAmPlaceholder")}
              className={errors.nameAm ? "border-red-500 focus-visible:ring-red-500" : ""}
            />
            {errors.nameAm && (
              <span className="text-xs text-red-500 font-medium">{errors.nameAm}</span>
            )}
          </div>

          {/* Site Name (English) */}
          <div className="space-y-1">
            <Label htmlFor="nameEn" className="text-sm font-semibold">
              {t("sites.form.nameEnLabel")} <span className="text-red-500">*</span>
            </Label>
            <Input
              id="nameEn"
              value={nameEn}
              onChange={(e) => setNameEn(e.target.value)}
              placeholder={t("sites.form.nameEnPlaceholder")}
              className={errors.nameEn ? "border-red-500 focus-visible:ring-red-500" : ""}
            />
            {nameEn.trim() && (
              <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
                {t("sites.form.previewLabel")} <span className="font-mono text-primary font-semibold">{toSnakeCase(nameEn)}</span>
              </p>
            )}
            {errors.nameEn && (
              <span className="text-xs text-red-500 font-medium">{errors.nameEn}</span>
            )}
          </div>

          {/* Site Key */}
          <div className="space-y-1">
            <Label htmlFor="key" className="text-sm font-semibold">
              {t("sites.form.keyLabel")} <span className="text-red-500">*</span>
            </Label>
            <Input
              id="key"
              value={key}
              onChange={(e) => setKey(e.target.value)}
               placeholder={t("sites.form.keyPlaceholder")}
              disabled={isEdit}
              className={errors.key ? "border-red-500 focus-visible:ring-red-500" : ""}
            />
            {!isEdit && (
              <p className="text-xs text-slate-400">
                {t("sites.form.keyHint")}
              </p>
            )}
            {errors.key && (
              <span className="text-xs text-red-500 font-medium">{errors.key}</span>
            )}
          </div>

          {/* Site Domain */}
          <div className="space-y-1">
            <Label htmlFor="domain" className="text-sm font-semibold">
              {t("sites.form.domainLabel")} <span className="text-red-500">*</span>
            </Label>
            <Input
              id="domain"
              value={domain}
              onChange={(e) => setDomain(e.target.value)}
               placeholder={t("sites.form.domainPlaceholder")}
              className={errors.domain ? "border-red-500 focus-visible:ring-red-500" : ""}
            />
            {errors.domain && (
              <span className="text-xs text-red-500 font-medium">{errors.domain}</span>
            )}
          </div>

          <DialogFooter className="pt-4 border-t gap-2 sm:gap-0">
            <Button
              type="button"
              variant="outline"
              onClick={onClose}
              disabled={isSubmitting}
              className="w-full sm:w-auto"
            >
              {t("common.cancel")}
            </Button>
            <Button
              type="submit"
              disabled={isSubmitting}
              className="w-full sm:w-auto"
            >
              {isSubmitting ? t("sites.form.saving") : isEdit ? t("sites.form.saveChanges") : t("sites.form.createSite")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
