"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/use-toast";
import Axios from "@/lib/Axios";
import useUserStore from "@/store/useUserStore";
import { useRouter } from "next/navigation";
import { Plus, Pencil, Trash2 } from "lucide-react";

type Product = {
  id: number;
  name: string;
  description?: string;
  amount?: number;
  postageServiceCharges?: number;
  isActive?: boolean;
};

type CreateProductDto = {
  name: string;
  description?: string;
  postageServiceCharges?: number;
};

type PostageServiceCharge = {
  id: number;
  name: string;
  description?: string;
  amount: number;
  isActive?: boolean;
};

type CreatePostageServiceChargeDto = {
  name: string;
  description?: string;
  amount: number;
};

type TabType = "products" | "postage";

const ProductsAndPostagePage = () => {
  const { toast } = useToast();
  const router = useRouter();
  const userData = useUserStore((state) => state.data);
  const [hydrated, setHydrated] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>("products");

  const [products, setProducts] = useState<Product[]>([]);
  const [isLoadingProducts, setIsLoadingProducts] = useState(false);
  const [newProduct, setNewProduct] = useState<CreateProductDto>({
    name: "",
    description: "",
    postageServiceCharges: undefined,
  });
  const [editingProductId, setEditingProductId] = useState<number | null>(null);
  const [editingProduct, setEditingProduct] = useState<CreateProductDto>({
    name: "",
    description: "",
    postageServiceCharges: undefined,
  });

  const [postageCharges, setPostageCharges] = useState<PostageServiceCharge[]>([]);
  const [isLoadingPostage, setIsLoadingPostage] = useState(false);
  const [newPostage, setNewPostage] = useState<CreatePostageServiceChargeDto>({
    name: "",
    description: "",
    amount: 0,
  });
  const [editingPostageId, setEditingPostageId] = useState<number | null>(null);
  const [editingPostage, setEditingPostage] = useState<CreatePostageServiceChargeDto>({
    name: "",
    description: "",
    amount: 0,
  });

  useEffect(() => {
    setHydrated(true);
  }, []);

  const isAdminOrOwner =
    userData?.role === "Admin" || userData?.role === "Owner";

  useEffect(() => {
    if (!hydrated) return;
    if (!userData || !userData.tokens?.access) {
      router.push("/login");
      return;
    }
    if (!isAdminOrOwner) {
      toast({
        title: "Access Denied",
        description: "Only Admin or Owner can manage products and postage.",
        variant: "destructive",
      });
      router.push("/customer");
    }
  }, [hydrated, userData, isAdminOrOwner, router, toast]);

  useEffect(() => {
    if (!hydrated || !isAdminOrOwner) return;
    fetchProducts();
    fetchPostageCharges();
  }, [hydrated, isAdminOrOwner]);

  // Sync editingProduct state when editingProductId changes
  useEffect(() => {
    if (editingProductId && products.length > 0) {
      const product = products.find((p) => p.id === editingProductId);
      if (product) {
        setEditingProduct({
          name: product.name || "",
          description: product.description || "",
          postageServiceCharges: product.postageServiceCharges !== undefined && product.postageServiceCharges !== null ? Number(product.postageServiceCharges) : undefined,
        });
      }
    }
  }, [editingProductId, products]);

  // Sync editingPostage state when editingPostageId changes
  useEffect(() => {
    if (editingPostageId && postageCharges.length > 0) {
      const charge = postageCharges.find((c) => c.id === editingPostageId);
      if (charge) {
        setEditingPostage({
          name: charge.name || "",
          description: charge.description || "",
          amount: charge.amount !== undefined && charge.amount !== null ? Number(charge.amount) : 0,
        });
      }
    }
  }, [editingPostageId, postageCharges]);

  const fetchProducts = async () => {
    try {
      setIsLoadingProducts(true);
      const res = await Axios.get<{ data: Product[]; total: number }>("/products/", {
        params: {
          isActive: true,
          limit: 1000,
        },
      });
      setProducts(res.data.data || []);
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to load products.",
        variant: "destructive",
      });
    } finally {
      setIsLoadingProducts(false);
    }
  };

  const handleCreateProduct = async () => {
    if (!newProduct.name.trim()) {
      toast({
        title: "Validation Error",
        description: "Product name is required.",
        variant: "destructive",
      });
      return;
    }
    try {
      const payload: CreateProductDto = {
        name: newProduct.name.trim(),
        description: newProduct.description?.trim() || undefined,
        postageServiceCharges: newProduct.postageServiceCharges !== undefined && newProduct.postageServiceCharges !== null ? Number(newProduct.postageServiceCharges) : undefined,
      };
      await Axios.post("/products/", payload);
      toast({
        title: "Success",
        description: "Product created successfully.",
      });
      setNewProduct({ name: "", description: "", postageServiceCharges: undefined });
      fetchProducts();
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to create product.",
        variant: "destructive",
      });
    }
  };

  const startEditProduct = (product: Product) => {
    // Set both states together to ensure they're in sync
    const editData: CreateProductDto = {
      name: product.name || "",
      description: product.description || "",
      postageServiceCharges: product.postageServiceCharges !== undefined && product.postageServiceCharges !== null ? Number(product.postageServiceCharges) : undefined,
    };
    
    // Set state - React will batch these updates
    setEditingProduct(editData);
    setEditingProductId(product.id);
  };

  const handleUpdateProduct = async () => {
    if (!editingProductId) return;
    if (!editingProduct.name.trim()) {
      toast({
        title: "Validation Error",
        description: "Product name is required.",
        variant: "destructive",
      });
      return;
    }
    try {
      const payload: CreateProductDto = {
        name: editingProduct.name.trim(),
        description: editingProduct.description?.trim() || undefined,
        postageServiceCharges: editingProduct.postageServiceCharges !== undefined && editingProduct.postageServiceCharges !== null ? Number(editingProduct.postageServiceCharges) : undefined,
      };
      await Axios.patch(`/products/${editingProductId}`, payload);
      toast({
        title: "Success",
        description: "Product updated successfully.",
      });
      setEditingProductId(null);
      setEditingProduct({
        name: "",
        description: "",
        postageServiceCharges: undefined,
      });
      fetchProducts();
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to update product.",
        variant: "destructive",
      });
    }
  };

  const handleDeleteProduct = async (id: number) => {
    try {
      await Axios.delete(`/products/${id}`);
      toast({
        title: "Success",
        description: "Product deleted successfully.",
      });
      fetchProducts();
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to delete product.",
        variant: "destructive",
      });
    }
  };

  const fetchPostageCharges = async () => {
    try {
      setIsLoadingPostage(true);
      const res = await Axios.get<{ data: PostageServiceCharge[]; total?: number }>(
        "/postage-service-charges",
      );
      setPostageCharges(res.data.data || []);
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message ||
          "Failed to load postage/service charges.",
        variant: "destructive",
      });
    } finally {
      setIsLoadingPostage(false);
    }
  };

  const handleCreatePostage = async () => {
    if (!newPostage.name.trim()) {
      toast({
        title: "Validation Error",
        description: "Name is required.",
        variant: "destructive",
      });
      return;
    }
    if (!newPostage.amount || isNaN(newPostage.amount)) {
      toast({
        title: "Validation Error",
        description: "Valid amount is required.",
        variant: "destructive",
      });
      return;
    }
    try {
      const payload: CreatePostageServiceChargeDto = {
        name: newPostage.name.trim(),
        description: newPostage.description?.trim() || undefined,
        amount: Number(newPostage.amount),
      };
      await Axios.post("/postage-service-charges", payload);
      toast({
        title: "Success",
        description: "Postage/Service charge created successfully.",
      });
      setNewPostage({ name: "", description: "", amount: 0 });
      fetchPostageCharges();
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message ||
          "Failed to create postage/service charge.",
        variant: "destructive",
      });
    }
  };

  const startEditPostage = (charge: PostageServiceCharge) => {
    setEditingPostageId(charge.id);
    setEditingPostage({
      name: charge.name || "",
      description: charge.description || "",
      amount: charge.amount !== undefined && charge.amount !== null ? Number(charge.amount) : 0,
    });
  };

  const handleUpdatePostage = async () => {
    if (!editingPostageId) return;
    if (!editingPostage.name.trim()) {
      toast({
        title: "Validation Error",
        description: "Name is required.",
        variant: "destructive",
      });
      return;
    }
    if (!editingPostage.amount || isNaN(editingPostage.amount)) {
      toast({
        title: "Validation Error",
        description: "Valid amount is required.",
        variant: "destructive",
      });
      return;
    }
    try {
      const payload: CreatePostageServiceChargeDto = {
        name: editingPostage.name.trim(),
        description: editingPostage.description?.trim() || undefined,
        amount: Number(editingPostage.amount),
      };
      await Axios.patch(`/postage-service-charges/${editingPostageId}`, payload);
      toast({
        title: "Success",
        description: "Postage/Service charge updated successfully.",
      });
      setEditingPostageId(null);
      setEditingPostage({
        name: "",
        description: "",
        amount: 0,
      });
      fetchPostageCharges();
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message ||
          "Failed to update postage/service charge.",
        variant: "destructive",
      });
    }
  };

  const handleDeletePostage = async (id: number) => {
    try {
      await Axios.delete(`/postage-service-charges/${id}`);
      toast({
        title: "Success",
        description: "Postage/Service charge deleted successfully.",
      });
      fetchPostageCharges();
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message ||
          "Failed to delete postage/service charge.",
        variant: "destructive",
      });
    }
  };

  if (!hydrated || !userData || !isAdminOrOwner) {
    return null;
  }

  return (
    <div className="py-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-semibold text-gray-800">
          Products & Postage Management
        </h1>
        <Button variant="outline" onClick={() => router.push("/customer")}>
          Back to Customers
        </Button>
      </div>

      <div className="flex gap-2 mb-6">
        <Button
          variant={activeTab === "products" ? "default" : "outline"}
          onClick={() => setActiveTab("products")}
        >
          Products
        </Button>
        <Button
          variant={activeTab === "postage" ? "default" : "outline"}
          onClick={() => setActiveTab("postage")}
        >
          Postage
        </Button>
      </div>

      {activeTab === "products" && (
        <div className="space-y-6">
          <div className="bg-white border rounded-md p-4">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Plus className="w-4 h-4" /> Add Product
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Input
                placeholder="Product name"
                value={newProduct.name}
                onChange={(e) =>
                  setNewProduct((prev) => ({ ...prev, name: e.target.value }))
                }
              />
              <Input
                placeholder="Description (optional)"
                value={newProduct.description}
                onChange={(e) =>
                  setNewProduct((prev) => ({
                    ...prev,
                    description: e.target.value,
                  }))
                }
              />
            </div>
            <div className="mt-4 flex justify-end">
              <Button onClick={handleCreateProduct}>Add Product</Button>
            </div>
          </div>

          <div className="bg-white border rounded-md p-4">
            <h2 className="text-lg font-semibold mb-4">All Products</h2>
            {isLoadingProducts ? (
              <p className="text-sm text-gray-500">Loading products...</p>
            ) : products.length === 0 ? (
              <p className="text-sm text-gray-500">No products found.</p>
            ) : (
              <div className="space-y-3">
                {products.map((product) => (
                  <div
                    key={product.id}
                    className="flex flex-col md:flex-row md:items-center justify-between gap-3 border rounded-md p-3"
                  >
                    {editingProductId === product.id ? (
                      <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
                        <input
                          type="text"
                          value={editingProduct.name || ""}
                          onChange={(e) =>
                            setEditingProduct((prev) => ({
                              ...prev,
                              name: e.target.value,
                            }))
                          }
                          placeholder="Product name"
                          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                        />
                        <input
                          type="text"
                          value={editingProduct.description || ""}
                          onChange={(e) =>
                            setEditingProduct((prev) => ({
                              ...prev,
                              description: e.target.value,
                            }))
                          }
                          placeholder="Description"
                          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                        />
                      </div>
                    ) : (
                      <div className="flex-1">
                        <p className="font-medium text-gray-800">
                          {product.name}
                        </p>
                        {product.description && (
                          <p className="text-sm text-gray-500">
                            {product.description}
                          </p>
                        )}
                      </div>
                    )}
                    <div className="flex items-center gap-2">
                      {editingProductId === product.id ? (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={handleUpdateProduct}
                          >
                            Save
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => {
                              setEditingProductId(null);
                              setEditingProduct({
                                name: "",
                                description: "",
                                postageServiceCharges: undefined,
                              });
                            }}
                          >
                            Cancel
                          </Button>
                        </>
                      ) : (
                        <>
                          <Button
                            size="icon"
                            variant="outline"
                            onClick={() => startEditProduct(product)}
                          >
                            <Pencil className="w-4 h-4" />
                          </Button>
                          <Button
                            size="icon"
                            variant="ghost"
                            onClick={() => handleDeleteProduct(product.id)}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        </>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {activeTab === "postage" && (
        <div className="space-y-6">
          <div className="bg-white border rounded-md p-4">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Plus className="w-4 h-4" /> Add Postage/Service Charge
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Input
                placeholder="Name"
                value={newPostage.name}
                onChange={(e) =>
                  setNewPostage((prev) => ({ ...prev, name: e.target.value }))
                }
              />
              <Input
                placeholder="Description (optional)"
                value={newPostage.description}
                onChange={(e) =>
                  setNewPostage((prev) => ({
                    ...prev,
                    description: e.target.value,
                  }))
                }
              />
              <Input
                placeholder="Amount"
                type="number"
                value={newPostage.amount === 0 ? "" : newPostage.amount}
                onChange={(e) =>
                  setNewPostage((prev) => ({
                    ...prev,
                    amount: Number(e.target.value),
                  }))
                }
              />
            </div>
            <div className="mt-4 flex justify-end">
              <Button onClick={handleCreatePostage}>
                Add Postage/Service Charge
              </Button>
            </div>
          </div>

          <div className="bg-white border rounded-md p-4">
            <h2 className="text-lg font-semibold mb-4">
              All Postage/Service Charges
            </h2>
            {isLoadingPostage ? (
              <p className="text-sm text-gray-500">
                Loading postage/service charges...
              </p>
            ) : postageCharges.length === 0 ? (
              <p className="text-sm text-gray-500">
                No postage/service charges found.
              </p>
            ) : (
              <div className="space-y-3">
                {postageCharges.map((charge) => (
                  <div
                    key={charge.id}
                    className="flex flex-col md:flex-row md:items-center justify-between gap-3 border rounded-md p-3"
                  >
                    {editingPostageId === charge.id ? (
                      <div className="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                        <input
                          type="text"
                          value={editingPostage.name || ""}
                          onChange={(e) =>
                            setEditingPostage((prev) => ({
                              ...prev,
                              name: e.target.value,
                            }))
                          }
                          placeholder="Name"
                          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                        />
                        <input
                          type="text"
                          value={editingPostage.description || ""}
                          onChange={(e) =>
                            setEditingPostage((prev) => ({
                              ...prev,
                              description: e.target.value,
                            }))
                          }
                          placeholder="Description"
                          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                        />
                        <input
                          type="number"
                          step="0.01"
                          min="0"
                          value={editingPostage.amount || ""}
                          onChange={(e) =>
                            setEditingPostage((prev) => ({
                              ...prev,
                              amount: e.target.value === "" ? 0 : Number(e.target.value),
                            }))
                          }
                          placeholder="Amount"
                          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                        />
                      </div>
                    ) : (
                      <div className="flex-1">
                        <p className="font-medium text-gray-800">
                          {charge.name}
                        </p>
                        <p className="text-sm text-gray-500">
                          £{Number(charge.amount).toFixed(2)}
                        </p>
                        {charge.description && (
                          <p className="text-xs text-gray-400">
                            {charge.description}
                          </p>
                        )}
                      </div>
                    )}
                    <div className="flex items-center gap-2">
                      {editingPostageId === charge.id ? (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={handleUpdatePostage}
                          >
                            Save
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => {
                              setEditingPostageId(null);
                              setEditingPostage({
                                name: "",
                                description: "",
                                amount: 0,
                              });
                            }}
                          >
                            Cancel
                          </Button>
                        </>
                      ) : (
                        <>
                          <Button
                            size="icon"
                            variant="outline"
                            onClick={() => startEditPostage(charge)}
                          >
                            <Pencil className="w-4 h-4" />
                          </Button>
                          <Button
                            size="icon"
                            variant="ghost"
                            onClick={() => handleDeletePostage(charge.id)}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        </>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default ProductsAndPostagePage;


