"use client";

import Button from "@/components/ui/buttons/Button";
import SectionWrapper from "@/components/ui/section/SectionWrapper";
import { Plus, MapPin } from "lucide-react";
import Loader from "@/components/ui/Loader/Loader";
import { useLocation } from "@/hooks/useLocation";
import LocationForm from "../location/modal/LocationForm";
import { LocationCard } from "../location/LocationCard";
import NotFound from "@/components/ui/NotFound";
import { useStateContext } from "@/context/StateContext";
import { useActions } from "@/hooks/useActions";


export default function Locations({ clientId }: { clientId: string }) {
  const {
    locations,
    expanded,
    toggleExpand,
  } = useLocation(clientId);


  const { handleEdit, handleDelete, handleNew, handleClose } = useActions(
    "Locations",
  );

  const { isOpen, loading, recordID } = useStateContext();

  return (
    <div className="flex-1 overflow-auto px-6 py-5">
      <SectionWrapper
        title="Locations"
        count={locations || []}
        countLabel="location"
        countLabelPlural="locations"
        button={
          <Button
            name="Add Location"
            variant="outline"
            size="sm"
            icon={Plus}
            onClick={handleNew}
          />
        }
      >
        {loading ? (
          <Loader />
        ) : locations?.length === 0 ? (
          <NotFound
            title="No Location yet"
            message='Click "Add Location" to add your first location.'
            icon={<MapPin className="w-6 h-6 text-gray-400" />}
          />
        ) : (
          <div className="space-y-2">
            {locations?.map((location, idx) => {
              const open = expanded.has(location.id);

              return (
                <LocationCard
                  key={location.id}
                  location={location}
                  idx={idx}
                  open={open}
                  toggleExpand={toggleExpand}
                  setEditTarget={handleEdit}
                  handleDelete={handleDelete}
                  handleDeleteDoc={handleDelete}
                />
              );
            })}
          </div>
        )}

        {isOpen && (
          <LocationForm
            key={recordID ?? 'new'}
            title={recordID ? "Edit Location" : "Add Location"}
            initial={undefined}
            onClose={handleClose}
          />
        )}

        {/* {editTarget && (
          <LocationForm
            title="Edit Location"
            initial={editTarget}
            onSave={handleEdit}
            onClose={() => setEditTarget(null)}
          />
        )} */}
      </SectionWrapper>
    </div>
  );
}
