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

export default function EditBranchModal({ isOpen, branch, onClose, onUpdated }) {
  const [form, setForm] = useState({
    branch_name: "",
    address: "",
    phone: "",
    description: "",
    geofence_location: "",
    geofence_polygon: null,
    latitude: null,
    longitude: null,
  });
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [showMap, setShowMap] = useState(false);

  useEffect(() => {
    if (!isOpen || !branch) return;
    setForm({
      branch_name: branch.name || branch.branch_name || "",
      address: branch.address || "",
      phone: branch.phone || "",
      description: branch.description || "",
      geofence_location: branch.geofence_location || "",
      geofence_polygon: branch.geofence_polygon || null,
      latitude: branch.latitude ?? null,
      longitude: branch.longitude ?? null,
    });
    setError("");
    setShowMap(false);
  }, [isOpen, branch]);

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

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

    const branchName = form.branch_name.trim();

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

    setSubmitting(true);
    setError("");

    try {
      const result = await updateBranch({
        branch_id: branch.branch_id,
        branch_name: branchName,
        address: form.address.trim(),
        phone: form.phone.trim(),
        description: form.description.trim(),
        geofence_location: form.geofence_location.trim(),
        geofence_polygon: form.geofence_polygon,
        latitude: form.latitude,
        longitude: form.longitude,
      });

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

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

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
      <div className="max-h-[calc(100vh-2rem)] w-full max-w-2xl overflow-y-auto bg-white shadow-xl rounded-2xl">
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 bg-slate-50/50">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">Edit Branch</h2>
            <p className="text-sm text-slate-500">Update branch details</p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="p-2 text-slate-400 transition-colors rounded-full hover:bg-slate-100 hover:text-slate-600"
          >
            <X size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {error ? (
            <div className="p-3 text-sm text-red-700 rounded-lg bg-red-50 border border-red-200">
              {error}
            </div>
          ) : null}

          <div>
            <label className="block mb-1 text-sm font-medium text-slate-700">
              Branch Name <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              required
              value={form.branch_name}
              onChange={(e) => updateField("branch_name", e.target.value)}
              placeholder="e.g. Main Street Branch"
              className="w-full px-3 py-2 text-sm transition-colors bg-white border rounded-lg border-slate-200 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium text-slate-700">
              Address <span className="text-slate-400">(Optional)</span>
            </label>
            <input
              type="text"
              value={form.address}
              onChange={(e) => updateField("address", e.target.value)}
              placeholder="e.g. 123 Main St, City"
              className="w-full px-3 py-2 text-sm transition-colors bg-white border rounded-lg border-slate-200 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium text-slate-700">
              Phone <span className="text-slate-400">(Optional)</span>
            </label>
            <input
              type="text"
              value={form.phone}
              onChange={(e) => updateField("phone", e.target.value)}
              placeholder="e.g. 555-0123"
              className="w-full px-3 py-2 text-sm transition-colors bg-white border rounded-lg border-slate-200 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium text-slate-700">
              Description <span className="text-slate-400">(Optional)</span>
            </label>
            <textarea
              value={form.description}
              onChange={(e) => updateField("description", e.target.value)}
              placeholder="Internal notes about this branch..."
              rows={3}
              className="w-full px-3 py-2 text-sm transition-colors bg-white border rounded-lg resize-none border-slate-200 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium text-slate-700">
              Geofence Location <span className="text-slate-400">(Optional)</span>
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={form.geofence_location}
                onChange={(e) => updateField("geofence_location", e.target.value)}
                placeholder="Branch address or location label"
                className="min-w-0 flex-1 px-3 py-2 text-sm bg-white border rounded-lg border-slate-200 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
              <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>
          </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: branch.latitude, lng: branch.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="flex justify-end gap-3 pt-4 mt-6 border-t border-slate-100">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium transition-colors border rounded-lg text-slate-700 bg-white border-slate-200 hover:bg-slate-50 hover:text-slate-900"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="px-4 py-2 text-sm font-medium text-white transition-colors bg-blue-600 rounded-lg shadow-sm hover:bg-blue-700 disabled:opacity-50 disabled:cursor-default"
            >
              {submitting ? "Saving..." : "Save Changes"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

EditBranchModal.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  branch: PropTypes.object,
  onClose: PropTypes.func.isRequired,
  onUpdated: PropTypes.func.isRequired,
};
