"use client";

import { useState, useEffect } from 'react';
import { Plus, Edit, Trash } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { toast } from 'sonner';
import { Product } from '../types';

export default function Products() {
    const [products, setProducts] = useState<Product[]>([]);
    const [loading, setLoading] = useState(true);
    const [isProductModalOpen, setIsProductModalOpen] = useState(false);
    const [isEditMode, setIsEditMode] = useState(false);
    const [currentProductId, setCurrentProductId] = useState<string | null>(null);
    const [newProduct, setNewProduct] = useState({
        plan: '',
        description: '',
        price: '',
        firm: '',
    });
    const [existingFirms, setExistingFirms] = useState<string[]>([]);
    const [existingPlans, setExistingPlans] = useState<{ plan: string, price: string }[]>([]);
    const [isNewFirm, setIsNewFirm] = useState(false);
    const [isNewPlan, setIsNewPlan] = useState(false);

    // اضافه: state باز و بسته بودن هر firm در اکوردئون
    const [openFirms, setOpenFirms] = useState<Record<string, boolean>>({});

    // Fetch products on component mount
    useEffect(() => {
        fetchProducts();
    }, []);

    useEffect(() => {
        if (products.length > 0) {
            // Extract unique firms
            const firms = Array.from(new Set(products.map(p => p.firm))).filter(Boolean);
            setExistingFirms(firms);

            // Extract unique plans with their prices
            const uniquePlans = Array.from(
                new Map(
                    products.map(p => [`${p.plan}-${p.price}`, { plan: p.plan, price: String(p.price) }])
                ).values()
            );
            setExistingPlans(uniquePlans);

            // هنگام بارگذاری محصولات، همه firmها را به صورت بسته قرار می‌دهیم
            const initialOpenStates: Record<string, boolean> = {};
            firms.forEach(firm => {
                initialOpenStates[firm] = false;
            });
            setOpenFirms(initialOpenStates);
        }
    }, [products]);

    const fetchProducts = async () => {
        try {
            setLoading(true);
            const response = await fetch('/api/products');
            const data = await response.json();
            setProducts(data);
        } catch (error) {
            console.error('Error fetching products:', error);
            toast("خطا در بارگذاری محصولات");
        } finally {
            setLoading(false);
        }
    };

    const handleProductInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setNewProduct(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleFirmSelect = (value: string) => {
        if (value === 'new-firm') {
            setIsNewFirm(true);
            setNewProduct(prev => ({
                ...prev,
                firm: ''
            }));
        } else {
            setIsNewFirm(false);
            setNewProduct(prev => ({
                ...prev,
                firm: value
            }));
        }
    };

    const handlePlanSelect = (value: string) => {
        if (value === 'new-plan') {
            setIsNewPlan(true);
            setNewProduct(prev => ({
                ...prev,
                plan: '',
                price: ''
            }));
        } else {
            const [plan, price] = value.split('|');
            setIsNewPlan(false);
            setNewProduct(prev => ({
                ...prev,
                plan: plan,
                price: price
            }));
        }
    };

    const handleAddProduct = async () => {
        try {
            if (!newProduct.plan || !newProduct.price || !newProduct.firm) {
                toast("لطفا همه فیلدها را پر کنید");
                return;
            }

            const payload = {
                ...newProduct,
                price: parseFloat(newProduct.price)
            };

            const response = await fetch('/api/products', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
            });

            if (response.ok) {
                toast("محصول با موفقیت اضافه شد");
                setIsProductModalOpen(false);
                resetForm();
                fetchProducts();
            } else {
                toast("خطا در اضافه کردن محصول");
            }
        } catch (error) {
            console.error('Error adding product:', error);
            toast("خطا در اضافه کردن محصول");
        }
    };

    const handleEditProduct = (product: Product) => {
        setIsEditMode(true);
        setCurrentProductId(product.id);
        setNewProduct({
            plan: product.plan,
            description: product.description || '',
            price: String(product.price),
            firm: product.firm,
        });
        setIsProductModalOpen(true);
    };

    const handleUpdateProduct = async () => {
        try {
            if (!newProduct.plan || !newProduct.price || !newProduct.firm || !currentProductId) {
                toast("لطفا همه فیلدها را پر کنید");
                return;
            }

            const payload = {
                ...newProduct,
                price: parseFloat(newProduct.price)
            };

            const response = await fetch(`/api/products/${currentProductId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
            });

            if (response.ok) {
                toast("محصول با موفقیت بروزرسانی شد");
                setIsProductModalOpen(false);
                resetForm();
                fetchProducts();
            } else {
                toast("خطا در بروزرسانی محصول");
            }
        } catch (error) {
            console.error('Error updating product:', error);
            toast("خطا در بروزرسانی محصول");
        }
    };
    const handleDeleteProduct = async (productId: string) => {
        if (!confirm('آیا از حذف این محصول اطمینان دارید؟')) {
            return;
        }

        try {
            const response = await fetch(`/api/products/${productId}`, {
                method: 'DELETE',
            });

            if (response.ok) {
                toast("محصول با موفقیت حذف شد");
                fetchProducts();
            } else {
                toast("خطا در حذف محصول");
            }
        } catch (error) {
            console.error('Error deleting product:', error);
            toast("خطا در حذف محصول");
        }
    };
    const resetForm = () => {
        setNewProduct({
            plan: '',
            description: '',
            price: '',
            firm: '',
        });
        setIsNewFirm(false);
        setIsNewPlan(false);
        setIsEditMode(false);
        setCurrentProductId(null);
    };

    const handleOpenAddModal = () => {
        resetForm();
        setIsProductModalOpen(true);
    };

    // Toggle باز و بسته کردن هر شرکتی که اکوردئون دارد
    const toggleFirmOpen = (firm: string) => {
        setOpenFirms(prev => ({
            ...prev,
            [firm]: !prev[firm],
        }));
    };





    // گروه‌بندی محصولات بر اساس شرکت
    const productsByFirm = products.reduce((acc, product) => {
        if (!acc[product.firm]) {
            acc[product.firm] = [];
        }
        acc[product.firm].push(product);
        return acc;
    }, {} as Record<string, Product[]>);

    const renderProductsTable = (productsToRender: Product[]) => (
        <Table>
            <TableHeader>
                <TableRow className="*:!text-right">
                    <TableHead>ID</TableHead>
                    <TableHead>پلن</TableHead>
                    <TableHead>توضیحات</TableHead>
                    <TableHead>قیمت</TableHead>
                    <TableHead>شرکت</TableHead>
                    <TableHead>تاریخ ایجاد</TableHead>
                    <TableHead>عملیات</TableHead>
                </TableRow>
            </TableHeader>
            <TableBody>
                {productsToRender.length === 0 ? (
                    <TableRow>
                        <TableCell colSpan={7} className="text-center py-4">
                            محصولی یافت نشد
                        </TableCell>
                    </TableRow>
                ) : (
                    productsToRender.map((product) => (
                        <TableRow key={product.id}>
                            <TableCell>{product.id}</TableCell>
                            <TableCell>{product.plan}</TableCell>
                            <TableCell className="max-w-[200px] truncate">
                                {product.description}
                            </TableCell>
                            <TableCell>${product.price}</TableCell>
                            <TableCell>{product.firm}</TableCell>
                            <TableCell>
                                {new Date(product.createdAt).toLocaleString()}
                            </TableCell>
                            <TableCell>
                                <div className="flex space-x-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => handleEditProduct(product)}
                                    >
                                        <Edit className="h-4 w-4 ml-1" /> ویرایش
                                    </Button>
                                    <Button
                                        variant="destructive"
                                        size="sm"
                                        onClick={() => handleDeleteProduct(product.id)}
                                    >
                                        <Trash className="h-4 w-4 ml-1" /> حذف
                                    </Button>
                                </div>
                            </TableCell>
                        </TableRow>
                    ))
                )}
            </TableBody>
        </Table>
    );


    return (
        <div className="w-full max-w-7xl mx-auto py-10">
            <div className="flex justify-between items-center mb-6">
                <h1 className="text-2xl font-bold">مدیریت محصولات</h1>
                <Button onClick={handleOpenAddModal}>
                    <Plus className="h-4 w-4 ml-1" /> افزودن محصول
                </Button>
            </div>

            <div>
                {loading ? (
                    <div className="text-center py-8">در حال بارگذاری...</div>
                ) : (
                    Object.keys(productsByFirm).length === 0 ? (
                        <div className="text-center py-8">هیچ محصولی وجود ندارد</div>
                    ) : (
                        Object.keys(productsByFirm).map(firm => {
                            const isOpen = openFirms[firm] ?? false;
                            return (
                                <div key={firm} className="mb-4 border rounded-md shadow-sm">
                                    <button
                                        type="button"
                                        onClick={() => toggleFirmOpen(firm)}
                                        className="w-full flex justify-between items-center bg-secondary text-white px-4 py-2 rounded-t-md select-none"
                                    >
                                        <span className="text-lg font-semibold">{firm}</span>
                                        <span className="text-2xl leading-none select-none">
                                            {isOpen ? '−' : '+'}
                                        </span>
                                    </button>
                                    {isOpen && (
                                        <div className="p-4 max-h-[400px] overflow-auto">
                                            {renderProductsTable(productsByFirm[firm])}
                                        </div>
                                    )}
                                </div>
                            );
                        })
                    )
                )}
            </div>

            <Dialog open={isProductModalOpen} onOpenChange={(open) => {
                if (!open) resetForm();
                setIsProductModalOpen(open);
            }}>
                <DialogContent className="sm:max-w-[425px]">
                    <DialogHeader>
                        <DialogTitle>{isEditMode ? 'ویرایش محصول' : 'افزودن محصول جدید'}</DialogTitle>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">

                        {/* شرکت */}
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="firm" className="text-right">
                                شرکت
                            </Label>
                            <div className="col-span-3">
                                {isEditMode ? (
                                    <Input
                                        id="firm"
                                        name="firm"
                                        value={newProduct.firm}
                                        onChange={handleProductInputChange}
                                    />
                                ) : (
                                    <>
                                        <Select
                                            onValueChange={handleFirmSelect}
                                            value={isNewFirm ? 'new-firm' : newProduct.firm || undefined}
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="انتخاب شرکت" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {existingFirms.map(firm => (
                                                    <SelectItem key={firm} value={firm}>
                                                        {firm}
                                                    </SelectItem>
                                                ))}
                                                <SelectItem value="new-firm">شرکت جدید</SelectItem>
                                            </SelectContent>
                                        </Select>

                                        {isNewFirm && (
                                            <Input
                                                id="firm"
                                                name="firm"
                                                value={newProduct.firm}
                                                onChange={handleProductInputChange}
                                                className="mt-2"
                                                placeholder="نام شرکت جدید"
                                            />
                                        )}
                                    </>
                                )}
                            </div>
                        </div>

                        {/* پلن */}
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="plan" className="text-right">
                                پلن
                            </Label>
                            <div className="col-span-3">
                                {isEditMode ? (
                                    <Input
                                        id="plan"
                                        name="plan"
                                        value={newProduct.plan}
                                        onChange={handleProductInputChange}
                                    />
                                ) : (
                                    <>
                                        <Select
                                            onValueChange={handlePlanSelect}
                                            value={isNewPlan ? 'new-plan' : (newProduct.plan && newProduct.price) ? `${newProduct.plan}|${newProduct.price}` : undefined}
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="انتخاب پلن" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {existingPlans.map(item => (
                                                    <SelectItem key={`${item.plan}-${item.price}`} value={`${item.plan}|${item.price}`}>
                                                        {item.plan} - ${item.price}
                                                    </SelectItem>
                                                ))}
                                                <SelectItem value="new-plan">پلن جدید</SelectItem>
                                            </SelectContent>
                                        </Select>

                                        {isNewPlan && (
                                            <Input
                                                id="plan"
                                                name="plan"
                                                value={newProduct.plan}
                                                onChange={handleProductInputChange}
                                                className="mt-2"
                                                placeholder="نام پلن جدید"
                                            />
                                        )}
                                    </>
                                )}
                            </div>
                        </div>

                        {/* قیمت */}
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="price" className="text-right">
                                قیمت
                            </Label>
                            <Input
                                id="price"
                                name="price"
                                type="number"
                                value={newProduct.price}
                                onChange={handleProductInputChange}
                                className="col-span-3"
                                placeholder="قیمت"
                            />
                        </div>

                        {/* توضیحات */}
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="description" className="text-right">
                                توضیحات
                            </Label>
                            <Textarea
                                id="description"
                                name="description"
                                value={newProduct.description}
                                onChange={handleProductInputChange}
                                className="col-span-3"
                                rows={3}
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button type="submit" onClick={isEditMode ? handleUpdateProduct : handleAddProduct}>
                            {isEditMode ? 'بروزرسانی' : 'ذخیره'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}