"use client";

import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Loader2 } from "lucide-react";
import Button from "@/components/ui/Button";
import FormSection from "@/components/ui/FormSection";
import ImagePicker from "@/components/ui/ImagePicker";
import Input from "@/components/ui/Input";
import Modal from "@/components/ui/Modal";

interface Business {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  logo: string | null;
  email: string | null;
  phone: string | null;
  address: string | null;
  isActive: boolean;
}

interface BusinessFormModalProps {
  business: Business | null;
  onSave: () => void;
  onClose: () => void;
}

function slugify(str: string) {
  return str.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").slice(0, 60);
}

export default function BusinessFormModal({ business, onSave, onClose }: BusinessFormModalProps) {
  const t = useTranslations("businesses");
  const tc = useTranslations("common");

  const isEdit = Boolean(business);

  const [name, setName] = useState(business?.name ?? "");
  const [slug, setSlug] = useState(business?.slug ?? "");
  const [description, setDescription] = useState(business?.description ?? "");
  const [logo, setLogo] = useState(business?.logo ?? "");
  const [email, setEmail] = useState(business?.email ?? "");
  const [phone, setPhone] = useState(business?.phone ?? "");
  const [address, setAddress] = useState(business?.address ?? "");
  const [isActive, setIsActive] = useState(business?.isActive ?? true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [slugManual, setSlugManual] = useState(isEdit);

  useEffect(() => {
    if (!slugManual && name) {
      setSlug(slugify(name));
    }
  }, [name, slugManual]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");

    try {
      const payload = { name, slug, description: description || undefined, logo: logo || undefined, email: email || undefined, phone: phone || undefined, address: address || undefined, isActive };
      const url = isEdit ? `/api/businesses/${business!.id}` : "/api/businesses";
      const method = isEdit ? "PATCH" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error ?? tc("somethingWrong"));
        return;
      }

      onSave();
    } catch {
      setError(tc("somethingWrong"));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      wide
      title={isEdit ? t("editBusiness") : t("addBusiness")}
      description={t("formHint")}
      onClose={onClose}
    >
      <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
        <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-5 sm:px-6">
          <FormSection title={t("identitySection")} hint={t("identityHint")}>
            <div className="grid gap-3.5 sm:grid-cols-2">
              <div className="sm:col-span-2">
                <Input
                  label={t("name")}
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder={t("namePlaceholder")}
                  required
                />
              </div>
              <Input
                label={t("slug")}
                value={slug}
                onChange={(e) => { setSlug(e.target.value); setSlugManual(true); }}
                placeholder="my-business"
                hint={t("slugHint")}
                hintLabel={tc("helpLabel")}
                required
              />
            </div>
            <ImagePicker
              compact
              label={t("logo")}
              hint={t("logoHint")}
              value={logo}
              onChange={setLogo}
            />
          </FormSection>

          <FormSection title={t("contactSection")} hint={t("contactHint")}>
            <div className="grid gap-3.5 sm:grid-cols-2">
              <Input
                label={t("email")}
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="contact@business.com"
              />
              <Input
                label={t("phone")}
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                placeholder="+1-555-0100"
              />
              <div className="sm:col-span-2">
                <Input
                  label={t("address")}
                  value={address}
                  onChange={(e) => setAddress(e.target.value)}
                  placeholder={t("addressPlaceholder")}
                />
              </div>
            </div>
          </FormSection>

          <FormSection title={t("descriptionSection")} hint={t("descriptionHint")}>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder={t("descriptionPlaceholder")}
              rows={3}
              className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] px-3 py-2.5 text-sm text-[var(--text)] placeholder:text-[var(--text-faint)] focus:border-[var(--accent)]/60 focus:outline-none focus:ring-2 focus:ring-[var(--accent)]/40"
            />
          </FormSection>

          <FormSection title={t("statusSection")}>
            <label className="flex cursor-pointer items-center gap-3">
              <input type="checkbox" checked={isActive} onChange={(e) => setIsActive(e.target.checked)} className="sr-only" />
              <div className={`relative h-5 w-9 rounded-full transition-colors ${isActive ? "bg-[var(--accent)]" : "bg-[var(--border)]"}`}>
                <span className={`absolute top-0.5 h-4 w-4 rounded-full bg-white shadow transition-transform ${isActive ? "translate-x-4" : "translate-x-0.5"}`} />
              </div>
              <span className="text-sm text-[var(--text)]">{t("activeStatus")}</span>
            </label>
          </FormSection>

          {error && <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-500">{error}</p>}
        </div>

        <div className="flex shrink-0 items-center justify-end gap-2.5 border-t border-[var(--border)] bg-[var(--bg)]/40 px-5 py-4 sm:px-6">
          <Button type="button" variant="secondary" onClick={onClose} disabled={saving} className="min-w-[96px]">
            {tc("cancel")}
          </Button>
          <Button type="submit" disabled={saving || !name.trim()} className="min-w-[110px]">
            {saving ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                {tc("saving")}
              </>
            ) : isEdit ? (
              tc("update")
            ) : (
              tc("create")
            )}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
