"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Plus, Search, ChevronLeft, ChevronRight as ChevronRightIcon, X } from "lucide-react";
import { toast } from "sonner";
import { useDebounce } from "../../../../../src/hooks/useDebounce";
import StoreTable from "./StoreTable";
import StoreFormDialog from "./StoreFormDialog";
import StoreViewDialog from "./StoreViewDialog";


interface Store {
  _id: string;
  name: string;
  // brand: string;
  address: string;
  // city: string;
  // state: string;
  // pincode: string;
  phone: string;

  openTime: string;
  closeTime: string;

  // workingDays: {
  //   monday: boolean;
  //   tuesday: boolean;
  //   wednesday: boolean;
  //   thursday: boolean;
  //   friday: boolean;
  //   saturday: boolean;
  //   sunday: boolean;
  // };

  // coordinates: {
  //   lat: number;
  //   lng: number;
  // };

  isActive: boolean;
  // isFlagship: boolean;

  createdAt?: string;
  updatedAt?: string;
}

type StoreFormData = Omit<Store, "_id" | "createdAt" | "updatedAt">;

const initialFormData: StoreFormData = {
  name: "",
  // brand: "dulhesaheb",
  address: "",
  // city: "",
  // state: "",
  // pincode: "",
  phone: "",
  openTime: "",
  closeTime: "",
  isActive: true,
  // workingDays: {
  //   monday: true,
  //   tuesday: true,
  //   wednesday: true,
  //   thursday: true,
  //   friday: true,
  //   saturday: true,
  //   sunday: false,
  // },
  // coordinates: {
  //   lat: 0,
  //   lng: 0,
  // },  
  // isFlagship: false,
};

export default function StoresManagement() {
  const [stores, setStores] = useState<Store[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [viewingStore, setViewingStore] = useState<Store | null>(null);
  const [editingStore, setEditingStore] = useState<Store | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [sortField, setSortField] = useState<"name" | "createdAt">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState({ total: 0, pages: 0, page: 1, limit: 10 });
  const [formData, setFormData] = useState<StoreFormData>(initialFormData);

  const debouncedSearch = useDebounce(search, 500);

  const fetchStores = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        sort: sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch }),
      });
      const response = await fetch(`/api/stores?${params}`);
      const result = await response.json();
      if (result.success) {
        setStores(result.data);
        setPagination(result.pagination);
      } else {
        toast.error("Failed to fetch stores");
      }
    } catch {
      toast.error("Error fetching stores");
    } finally {
      setLoading(false);
    }
  }, [page, limit, sortField, sortOrder, debouncedSearch]);

  useEffect(() => {
    fetchStores();
  }, [fetchStores]);

  const resetForm = useCallback(() => {
    setFormData(initialFormData);
  }, []);

  const handleSearch = useCallback((value: string) => {
    setSearch(value);
    setPage(1);
  }, []);

  const handleLimitChange = useCallback((value: string) => {
    setLimit(parseInt(value));
    setPage(1);
  }, []);

  const handleSort = useCallback((field: "name" | "createdAt") => {
    if (sortField === field) {
      setSortOrder(o => o === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortOrder(field === "name" ? "asc" : "desc");
    }
    setPage(1);
  }, [sortField]);

  const handleView = useCallback((store: Store) => {
    setViewingStore(store);
    setIsViewDialogOpen(true);
  }, []);

  const handleEdit = useCallback((store: Store) => {
    setEditingStore(store);

    setFormData({
      name: store.name,
      // brand: store.brand,
      address: store.address,
      // city: store.city,
      // state: store.state,
      // pincode: store.pincode,
      phone: store.phone,

      openTime: store.openTime,
      closeTime: store.closeTime,

      // workingDays: {
      //   monday: store.workingDays?.monday ?? true,
      //   tuesday: store.workingDays?.tuesday ?? true,
      //   wednesday: store.workingDays?.wednesday ?? true,
      //   thursday: store.workingDays?.thursday ?? true,
      //   friday: store.workingDays?.friday ?? true,
      //   saturday: store.workingDays?.saturday ?? true,
      //   sunday: store.workingDays?.sunday ?? false,
      // },

      // coordinates: {
      //   lat: store.coordinates?.lat ?? 0,
      //   lng: store.coordinates?.lng ?? 0,
      // },

      isActive: store.isActive,
      // isFlagship: store.isFlagship,
    });

    setIsDialogOpen(true);
  }, []);

  const handleDelete = useCallback(async (storeId: string) => {
    if (!confirm("Are you sure you want to delete this store?")) return;
    try {
      const response = await fetch(`/api/stores/${storeId}`, { method: "DELETE" });
      const result = await response.json();
      if (result.success) {
        toast.success("Store deleted successfully");
        if (stores.length === 1 && page > 1) {
          setPage(p => p - 1);
        } else {
          fetchStores();
        }
      } else {
        toast.error(result.error || "Failed to delete store");
      }
    } catch {
      toast.error("Error deleting store");
    }
  }, [fetchStores, stores.length, page]);

  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const url = editingStore ? `/api/stores/${editingStore._id}` : "/api/stores";
      const method = editingStore ? "PUT" : "POST";

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

      if (result.success) {
        toast.success(editingStore ? "Store updated successfully" : "Store created successfully");
        setIsDialogOpen(false);
        setEditingStore(null);
        resetForm();
        fetchStores();
      } else {
        toast.error(result.error || "Failed to save store");
      }
    } catch {
      toast.error("Error saving store");
    } finally {
      setSubmitting(false);
    }
  }, [editingStore, formData, fetchStores, resetForm]);

  return (
    <div className="space-y-6">
      {/* Toolbar */}
      <div className="flex justify-between items-center">
        <Button
          onClick={() => {
            resetForm();
            setEditingStore(null);
            setIsDialogOpen(true);
          }}
        >
          <Plus className="w-4 h-4 mr-1" />
          Add Store
        </Button>
      </div>

      {/* Search + Limit */}
      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            placeholder="Search stores..."
            value={search}
            onChange={e => handleSearch(e.target.value)}
            className="pl-10 pr-8"
          />
          <X
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
            onClick={() => handleSearch("")}
          />
        </div>
        <div className="flex items-center gap-2">
          <Label className="text-sm whitespace-nowrap">Show:</Label>
          <select
            value={limit.toString()}
            onChange={e => handleLimitChange(e.target.value)}
            className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"
          >
            <option value="6">6</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </div>
      </div>

      {/* Table */}
      <StoreTable
        stores={stores}
        loading={loading}
        pagination={pagination}
        sortField={sortField}
        sortOrder={sortOrder}
        handleSort={handleSort}
        handleView={handleView}
        handleEdit={handleEdit}
        handleDelete={handleDelete}
      />

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} results
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => setPage(p => p - 1)} disabled={page === 1}>
              <ChevronLeft className="h-4 w-4" /> Previous
            </Button>
            <span className="text-sm">Page {page} of {pagination.pages}</span>
            <Button variant="outline" size="sm" onClick={() => setPage(p => p + 1)} disabled={page === pagination.pages}>
              Next <ChevronRightIcon className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Dialogs */}
      {isDialogOpen && (
        <StoreFormDialog
          open={isDialogOpen}
          onOpenChange={setIsDialogOpen}
          editingStore={editingStore}
          formData={formData}
          setFormData={setFormData}
          handleSubmit={handleSubmit}
          loading={submitting}
          resetForm={resetForm}
        />
      )}

      {isViewDialogOpen && (
        <StoreViewDialog
          open={isViewDialogOpen}
          onOpenChange={setIsViewDialogOpen}
          viewingStore={viewingStore}
          handleEdit={handleEdit}
          handleDelete={handleDelete}
        />
      )}
    </div>
  );
}