"use client";

import { useState } 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 Input from "@/components/ui/Input";
import Modal from "@/components/ui/Modal";

interface Franchise {
  id: string;
  name: string;
}

interface Location {
  id: string;
  name: string;
  address: string | null;
  city: string | null;
  country: string | null;
  phone: string | null;
  isMain: boolean;
  isActive: boolean;
  franchiseId: string | null;
}

interface LocationFormModalProps {
  businessId: string;
  location: Location | null;
  franchises: Franchise[];
  onSave: () => void;
  onClose: () => void;
}

export default function LocationFormModal({ businessId, location, franchises, onSave, onClose }: LocationFormModalProps) {
  const t = useTranslations("locations");
  const tc = useTranslations("common");

  const isEdit = Boolean(location);
  const [name, setName] = useState(location?.name ?? "");
  const [address, setAddress] = useState(location?.address ?? "");
  const [city, setCity] = useState(location?.city ?? "");
  const [country, setCountry] = useState(location?.country ?? "");
  const [phone, setPhone] = useState(location?.phone ?? "");
  const [isMain, setIsMain] = useState(location?.isMain ?? false);
  const [isActive, setIsActive] = useState(location?.isActive ?? true);
  const [franchiseId, setFranchiseId] = useState(location?.franchiseId ?? "");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const url = isEdit
        ? `/api/businesses/${businessId}/locations/${location!.id}`
        : `/api/businesses/${businessId}/locations`;
      const method = isEdit ? "PATCH" : "POST";
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          address: address || undefined,
          city: city || undefined,
          country: country || undefined,
          phone: phone || undefined,
          isMain,
          isActive,
          franchiseId: franchiseId || null,
        }),
      });
      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("editLocation") : t("addLocation")}
      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("detailsSection")} hint={t("detailsHint")}>
            <Input label={t("name")} value={name} onChange={(e) => setName(e.target.value)} placeholder={t("namePlaceholder")} required />
            <Input label={t("phone")} value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+1-555-0100" />
          </FormSection>

          <FormSection title={t("addressSection")} hint={t("addressHint")}>
            <Input label={t("address")} value={address} onChange={(e) => setAddress(e.target.value)} placeholder="123 Main St" />
            <div className="grid gap-3.5 sm:grid-cols-2">
              <Input label={t("city")} value={city} onChange={(e) => setCity(e.target.value)} placeholder="New York" />
              <Input label={t("country")} value={country} onChange={(e) => setCountry(e.target.value)} placeholder="USA" />
            </div>
          </FormSection>

          {franchises.length > 0 && (
            <FormSection title={t("assignmentSection")} hint={t("assignmentHint")}>
              <select
                value={franchiseId}
                onChange={(e) => setFranchiseId(e.target.value)}
                className="w-full cursor-pointer rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] px-3 py-2.5 text-sm text-[var(--text)] focus:border-[var(--accent)]/60 focus:outline-none focus:ring-2 focus:ring-[var(--accent)]/40"
              >
                <option value="">{t("directLocation")}</option>
                {franchises.map((f) => (
                  <option key={f.id} value={f.id}>{f.name}</option>
                ))}
              </select>
            </FormSection>
          )}

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