"use client";

import { useState, useEffect } from 'react';
import { Plus, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
    DialogDescription,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import { toast } from 'sonner';
import { Wallet } from '../types';

export default function Wallets() {
    const [wallets, setWallets] = useState<Wallet[]>([]);
    const [loading, setLoading] = useState(true);
    const [isWalletModalOpen, setIsWalletModalOpen] = useState(false);
    const [isEditMode, setIsEditMode] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [selectedWalletId, setSelectedWalletId] = useState<number | null>(null);
    const [newWallet, setNewWallet] = useState({
        network: '',
        name: '',
        address: '',
        description: '',
    });

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

    const fetchWallets = async () => {
        try {
            setLoading(true);
            const response = await fetch('/api/wallets');
            const data = await response.json();
            setWallets(data);
        } catch (error) {
            console.error('Error fetching wallets:', error);
            toast("خطا در بارگذاری کیف پول‌ها");
        } finally {
            setLoading(false);
        }
    };

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

    const resetForm = () => {
        setNewWallet({
            network: '',
            name: '',
            address: '',
            description: '',
        });
        setIsEditMode(false);
        setSelectedWalletId(null);
    };

    const handleAddWallet = async () => {
        try {
            const response = await fetch('/api/wallets', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(newWallet),
            });

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

    const handleEditClick = (wallet: Wallet) => {
        setIsEditMode(true);
        setSelectedWalletId(wallet.id);
        setNewWallet({
            network: wallet.network,
            name: wallet.name,
            address: wallet.address,
            description: wallet.description || '',
        });
        setIsWalletModalOpen(true);
    };

    const handleUpdateWallet = async () => {
        if (!selectedWalletId) return;
        
        try {
            const response = await fetch(`/api/wallets/${selectedWalletId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(newWallet),
            });

            if (response.ok) {
                toast("کیف پول با موفقیت ویرایش شد");
                setIsWalletModalOpen(false);
                resetForm();
                fetchWallets();
            } else {
                toast("خطا در ویرایش کیف پول");
            }
        } catch (error) {
            console.error('Error updating wallet:', error);
            toast("خطا در ویرایش کیف پول");
        }
    };

    const handleDeleteClick = (walletId: number) => {
        setSelectedWalletId(walletId);
        setIsDeleteDialogOpen(true);
    };

    const handleDeleteWallet = async () => {
        if (!selectedWalletId) return;
        
        try {
            const response = await fetch(`/api/wallets/${selectedWalletId}`, {
                method: 'DELETE',
            });

            if (response.ok) {
                toast("کیف پول با موفقیت حذف شد");
                setIsDeleteDialogOpen(false);
                setSelectedWalletId(null);
                fetchWallets();
            } else {
                toast("خطا در حذف کیف پول");
            }
        } catch (error) {
            console.error('Error deleting wallet:', error);
            toast("خطا در حذف کیف پول");
        }
    };

    const handleModalClose = () => {
        setIsWalletModalOpen(false);
        resetForm();
    };

    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={() => {
                    resetForm();
                    setIsWalletModalOpen(true);
                }}>
                    <Plus className="h-4 w-4 ml-2" /> افزودن کیف پول
                </Button>
            </div>

            <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow className="*:!text-right">
                            <TableHead>ID</TableHead>
                            <TableHead>شبکه</TableHead>
                            <TableHead>نام</TableHead>
                            <TableHead>آدرس</TableHead>
                            <TableHead>توضیحات</TableHead>
                            <TableHead>تاریخ ایجاد</TableHead>
                            <TableHead>عملیات</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {loading ? (
                            <TableRow>
                                <TableCell colSpan={7} className="text-center py-4">
                                    در حال بارگذاری...
                                </TableCell>
                            </TableRow>
                        ) : wallets.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={7} className="text-center py-4">
                                    کیف پولی یافت نشد
                                </TableCell>
                            </TableRow>
                        ) : (
                            wallets.map((wallet) => (
                                <TableRow key={wallet.id}>
                                    <TableCell>{wallet.id}</TableCell>
                                    <TableCell>{wallet.network}</TableCell>
                                    <TableCell>{wallet.name}</TableCell>
                                    <TableCell className="max-w-[150px] truncate">
                                        {wallet.address}
                                    </TableCell>
                                    <TableCell className="max-w-[200px] truncate">
                                        {wallet.description}
                                    </TableCell>
                                    <TableCell>
                                        {new Date(wallet.createdAt).toLocaleString()}
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex space-x-2 rtl:space-x-reverse">
                                            <Button 
                                                variant="outline" 
                                                size="sm" 
                                                onClick={() => handleEditClick(wallet)}
                                            >
                                                <Pencil className="h-4 w-4" /> 
                                            </Button>
                                            <Button 
                                                variant="outline" 
                                                size="sm"
                                                className="text-red-500 hover:text-red-600"
                                                onClick={() => handleDeleteClick(wallet.id)}
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {/* Add/Edit Wallet Modal */}
            <Dialog open={isWalletModalOpen} onOpenChange={handleModalClose}>
                <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="network" className="text-right">
                                شبکه
                            </Label>
                            <Input
                                id="network"
                                name="network"
                                value={newWallet.network}
                                onChange={handleWalletInputChange}
                                className="col-span-3"
                                placeholder="مثال: BEP20"
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="name" className="text-right">
                                نام
                            </Label>
                            <Input
                                id="name"
                                name="name"
                                value={newWallet.name}
                                onChange={handleWalletInputChange}
                                className="col-span-3"
                                placeholder="مثال: تتر بایننس"
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="address" className="text-right">
                                آدرس
                            </Label>
                            <Input
                                id="address"
                                name="address"
                                value={newWallet.address}
                                onChange={handleWalletInputChange}
                                className="col-span-3"
                                placeholder="0x..."
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="walletDescription" className="text-right">
                                توضیحات
                            </Label>
                            <Textarea
                                id="walletDescription"
                                name="description"
                                value={newWallet.description}
                                onChange={handleWalletInputChange}
                                className="col-span-3"
                                rows={3}
                                placeholder="مثال: آدرس ولت تتر شبکه بایننس"
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button type="submit" onClick={isEditMode ? handleUpdateWallet : handleAddWallet}>
                            {isEditMode ? 'ویرایش' : 'ذخیره'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Delete Confirmation Dialog */}
            <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
                <DialogContent className="sm:max-w-[425px]">
                    <DialogHeader>
                        <DialogTitle>حذف کیف پول</DialogTitle>
                        <DialogDescription>
                            آیا از حذف این کیف پول اطمینان دارید؟ این عملیات قابل بازگشت نیست.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>
                            انصراف
                        </Button>
                        <Button variant="destructive" onClick={handleDeleteWallet}>
                            حذف
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}