import { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { Map as MapIcon, X } from "lucide-react";
import { createBranch } from "../api/brandApi";
import GeofenceMap from "./GeofenceMap";
import ManagerDropdown from "./ManagerDropdown";

const initialForm = {
  name: "",
  address: "",
  phone: "",
  description: "",
  assigned_employee_id: "",
  geofence_location: "",
  geofence_polygon: null,
  latitude: null,
  longitude: null,
};

export default function BranchFormModal({ isOpen, brand, onClose, onCreated }) {
  const [form, setForm] = useState(initialForm);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [showMap, setShowMap] = useState(false);

  useEffect(() => {
    if (!isOpen) return;
    setForm(initialForm);
    setError("");
    setSubmitting(false);
    setShowMap(false);
  }, [isOpen, brand?.brand_id]);

  const updateField = (field, value) => {
    setForm((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!brand?.brand_id) {
      setError("Selected brand is missing.");
      return;
    }

    const branchName = form.name.trim();

    if (!branchName) {
      setError("Branch name is required.");
      return;
    }

    setSubmitting(true);
    setError("");

    try {
      const result = await createBranch({
        brand_id: Number(brand.brand_id),
        name: branchName,
        address: form.address.trim(),
        phone: form.phone.trim(),
        description: form.description.trim(),
        assigned_employee_id: form.assigned_employee_id.trim() || null,
        geofence_location: form.geofence_location.trim(),
        geofence_polygon: form.geofence_polygon,
        latitude: form.latitude,
        longitude: form.longitude,
      });

      onCreated?.(result);
    } catch (err) {
      setError(err?.message || "Failed to create branch.");
    } finally {
      setSubmitting(false);
    }
  };

  if (!isOpen || !brand) return null;

  return (
    <div className="fixed inset-0 z-[65] flex items-center justify-center bg-black/45 p-4">
      <form
        onSubmit={handleSubmit}
        className="max-h-[calc(100vh-2rem)] w-full max-w-2xl overflow-y-auto rounded-xl bg-white p-6 shadow-xl"
      >
        <div className="mb-5 flex items-start justify-between gap-4">
          <div>
            <h3 className="text-xl font-semibold text-slate-900">
              Add Branch
            </h3>
            <p className="mt-1 text-sm text-slate-500">
              Create a branch under{" "}
              <span className="font-semibold text-slate-700">
                {brand.brand_name}
              </span>
              .
            </p>
            <p className="mt-1 font-mono text-xs text-slate-400">
              {brand.brand_code}
            </p>
          </div>

          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="rounded-md p-1 text-slate-500 hover:bg-slate-100 hover:text-slate-800 disabled:opacity-60"
            aria-label="Close branch modal"
          >
            <X size={18} />
          </button>
        </div>

        {error ? (
          <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
            {error}
          </div>
        ) : null}

        <div className="space-y-4">
          <label className="block">
            <span className="mb-1 block text-sm font-medium text-slate-700">
              Branch Name
            </span>
            <input
              value={form.name}
              onChange={(event) => updateField("name", event.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
              placeholder="Example: CDO Main Branch"
              required
            />
          </label>

          <label className="block">
            <span className="mb-1 block text-sm font-medium text-slate-700">
              Address
            </span>
            <input
              value={form.address}
              onChange={(event) => updateField("address", event.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
              placeholder="Optional"
            />
          </label>

          <div className="grid gap-3 sm:grid-cols-2">
            <label className="block">
              <span className="mb-1 block text-sm font-medium text-slate-700">
                Phone
              </span>
              <input
                value={form.phone}
                onChange={(event) => updateField("phone", event.target.value)}
                className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
                placeholder="Optional"
              />
            </label>

            <label className="block">
              <span className="mb-1 block text-sm font-medium text-slate-700">
                Manager Employee ID
              </span>
              <ManagerDropdown
                value={form.assigned_employee_id}
                onChange={(value) => updateField("assigned_employee_id", value)}
              />
            </label>
          </div>

          <label className="block">
            <span className="mb-1 block text-sm font-medium text-slate-700">
              Description
            </span>
            <textarea
              value={form.description}
              onChange={(event) =>
                updateField("description", event.target.value)
              }
              className="min-h-[90px] w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
              placeholder="Optional"
            />
          </label>

          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Geofence Location <span className="text-slate-400">(Optional)</span>
            </label>
            <div className="flex gap-2">
              <input
                value={form.geofence_location}
                onChange={(event) => updateField("geofence_location", event.target.value)}
                className="min-w-0 flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
                placeholder="Branch address or location label"
              />
              <button
                type="button"
                onClick={() => setShowMap((visible) => !visible)}
                className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-sm font-medium ${
                  showMap || form.geofence_polygon
                    ? "border-blue-200 bg-blue-50 text-blue-700"
                    : "border-slate-200 bg-white text-slate-700 hover:bg-slate-50"
                }`}
              >
                <MapIcon size={16} />
                {form.geofence_polygon ? "Edit Polygon" : "Draw Polygon"}
              </button>
            </div>
            {form.geofence_polygon && !showMap ? (
              <p className="mt-1 text-xs font-medium text-emerald-600">
                Branch geofence polygon is set.
              </p>
            ) : null}
          </div>

          {showMap ? (
            <div>
              <p className="mb-2 text-xs text-slate-500">
                Draw the permitted clock-in boundary for this branch.
              </p>
              <GeofenceMap
                initialPolygon={form.geofence_polygon}
                center={{ lat: brand.latitude, lng: brand.longitude }}
                onChange={(polygon) => updateField("geofence_polygon", polygon)}
                onLocationSelect={(location) =>
                  setForm((current) => ({
                    ...current,
                    geofence_location: location.display_name,
                    latitude: location.latitude,
                    longitude: location.longitude,
                  }))
                }
              />
            </div>
          ) : null}

          <div className="max-w-full min-w-0 overflow-hidden whitespace-normal break-words rounded-lg border border-blue-100 bg-blue-50 px-3 py-2 text-xs leading-5 text-blue-700">
            Branches are brand-scoped. Employees can only be assigned to this
            branch if they also belong to{" "}
            <span className="break-all font-semibold">{brand.brand_name}</span>.
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="rounded bg-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-300 disabled:opacity-60"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={submitting}
            className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
          >
            {submitting ? "Creating..." : "Create Branch"}
          </button>
        </div>
      </form>
    </div>
  );
}

BranchFormModal.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  brand: PropTypes.object,
  onClose: PropTypes.func.isRequired,
  onCreated: PropTypes.func,
};
