"use client";

import { useState } from "react";
import Layout from "@/components/kokonutui/layout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Send } from "lucide-react";

export default function WithdrawalsPageClient({ balances, withdrawals }) {
  const [withdrawalData, setWithdrawalData] = useState({
    currency: "bitcoin",
    address: "",
    amount: "",
  });

  const handleWithdraw = async () => {
    const { currency, address, amount } = withdrawalData;

    if (!currency || !address || !amount || parseFloat(amount) <= 0) {
      alert("Please provide valid withdrawal details.");
      return;
    }

    try {
      const authToken = document.cookie.split("authToken=")[1];
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/withdraw`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${authToken}`,
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({ currency, address, amount }),
      });

      if (!res.ok) throw new Error("Failed to process withdrawal");

      alert("Withdrawal request submitted successfully!");
      setWithdrawalData({ currency: "bitcoin", address: "", amount: "" });
    } catch (error) {
      console.error("Error processing withdrawal:", error);
      alert("Failed to process withdrawal. Please try again.");
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setWithdrawalData({ ...withdrawalData, [name]: value });
  };

  return (
    <Layout>
      <div className="space-y-6">
        <h1 className="text-2xl font-semibold text-gray-900 dark:text-white">
          Withdraw Funds
        </h1>

        {/* Balances Display */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <Card className="shadow-sm bg-white dark:bg-zinc-800 border border-gray-200 dark:border-gray-700">
            <CardHeader>
              <CardTitle>Bitcoin Balance</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-lg font-semibold text-gray-900 dark:text-white">
                {balances.bitcoin} BTC
              </p>
            </CardContent>
          </Card>

          <Card className="shadow-sm bg-white dark:bg-zinc-800 border border-gray-200 dark:border-gray-700">
            <CardHeader>
              <CardTitle>Litecoin Balance</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-lg font-semibold text-gray-900 dark:text-white">
                {balances.litecoin} LTC
              </p>
            </CardContent>
          </Card>

          <Card className="shadow-sm bg-white dark:bg-zinc-800 border border-gray-200 dark:border-gray-700">
            <CardHeader>
              <CardTitle>Monero Balance</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-lg font-semibold text-gray-900 dark:text-white">
                {balances.monero} XMR
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Withdrawal Form */}
        <div className="bg-white dark:bg-zinc-800 p-6 rounded-lg shadow border border-gray-200 dark:border-gray-700 space-y-4">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            Request Withdrawal
          </h2>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                Currency
              </label>
              <Select
                value={withdrawalData.currency}
                onValueChange={(value) =>
                  setWithdrawalData({ ...withdrawalData, currency: value })
                }
              >
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Select Currency" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="bitcoin">Bitcoin</SelectItem>
                  <SelectItem value="litecoin">Litecoin</SelectItem>
                  <SelectItem value="monero">Monero</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                Withdrawal Address
              </label>
              <Input
                name="address"
                placeholder="Enter the withdrawal address"
                value={withdrawalData.address}
                onChange={handleChange}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                Amount
              </label>
              <Input
                name="amount"
                placeholder="Enter the amount to withdraw"
                type="number"
                min="0"
                step="any"
                value={withdrawalData.amount}
                onChange={handleChange}
              />
            </div>
          </div>

          <Button onClick={handleWithdraw} className="w-full">
            <Send className="mr-2 h-5 w-5" />
            Request Withdrawal
          </Button>
        </div>

        {/* Withdrawals History */}
        <div className="bg-white dark:bg-zinc-800 p-6 rounded-lg shadow border border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Withdrawals History
          </h2>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Currency</TableHead>
                <TableHead>Amount</TableHead>
                <TableHead>Address</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {withdrawals.length > 0 ? (
                withdrawals.map((withdrawal) => (
                  <TableRow key={withdrawal.id}>
                    <TableCell>{withdrawal.date}</TableCell>
                    <TableCell>{withdrawal.currency.toUpperCase()}</TableCell>
                    <TableCell>{withdrawal.amount}</TableCell>
                    <TableCell>{withdrawal.address}</TableCell>
                    <TableCell>{withdrawal.status}</TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={5} className="text-center">
                    No withdrawals found.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>
    </Layout>
  );
}