"use client"
import { useEffect, useState, useCallback } from "react"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import https from "@/services/https"
import { getCreditAdditions } from "@/services/api" // Import the new API function
import * as XLSX from "xlsx";
import { Download } from 'lucide-react';

// Helper function to format date to YYYY-MM-DD
const formatDate = (date) => date.toISOString().split('T')[0];

// Helper function to get default date range (1 month from current date)
const getDefaultDateRange = () => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setMonth(startDate.getMonth() - 1); // One month ago
  return {
    startDate: formatDate(startDate),
    endDate: formatDate(endDate),
  };
};

export default function PaymentsPage() {
  const [allPayments, setAllPayments] = useState([])
  const [paygoPayments, setPaygoPayments] = useState([])
  const [creditAdditions, setCreditAdditions] = useState([]) // New state for credit additions
  const [loading, setLoading] = useState(true)
  const [loadingCredit, setLoadingCredit] = useState(true) // New loading state for credit additions
  const [error, setError] = useState(null)
  const [errorCredit, setErrorCredit] = useState(null) // New error state for credit additions

  const [paygoFromDate, setPaygoFromDate] = useState(() => {
    const defaultRange = getDefaultDateRange();
    return defaultRange.startDate;
  });
  const [paygoToDate, setPaygoToDate] = useState(() => {
    const defaultRange = getDefaultDateRange();
    return defaultRange.endDate;
  });

  const [creditFromDate, setCreditFromDate] = useState(() => { // New date states for credit additions
    const defaultRange = getDefaultDateRange();
    return defaultRange.startDate;
  });
  const [creditToDate, setCreditToDate] = useState(() => { // New date states for credit additions
    const defaultRange = getDefaultDateRange();
    return defaultRange.endDate;
  });

  const fetchAllPayments = async () => {
    try {
      const token = localStorage.getItem("token")
      const response = await fetch(`${https.baseUrl}/payments`, {
        headers: { "x-auth-token": token },
      })
      const data = await response.json()
      setAllPayments(data)
    } catch (error) {
      setError(error)
    } finally {
      // Only set global loading to false if all initial fetches are done
      // For now, we'll manage individual loading states
    }
  }

  const fetchPaygoPayments = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const token = localStorage.getItem("token")
      let url = `${https.baseUrl}/payments/devices/payments`;
      const params = new URLSearchParams();
      if (paygoFromDate) params.append('FROM', new Date(paygoFromDate).toISOString());
      if (paygoToDate) params.append('TO', new Date(paygoToDate).toISOString());
      if (params.toString()) {
        url += `?${params.toString()}`;
      }

      const response = await fetch(url, {
        headers: { "x-auth-token": token },
      })
      const data = await response.json()
      setPaygoPayments(data.payments)
    } catch (error) {
      setError(error)
    } finally {
      setLoading(false)
    }
  }, [paygoFromDate, paygoToDate])

  const fetchCreditAdditions = useCallback(async () => { // New fetch function for credit additions
    setLoadingCredit(true)
    setErrorCredit(null)
    try {
      const data = await getCreditAdditions(creditFromDate, creditToDate);
      setCreditAdditions(data);
    } catch (err) {
      setErrorCredit("Failed to fetch credit additions.");
      console.error(err);
    } finally {
      setLoadingCredit(false);
    }
  }, [creditFromDate, creditToDate]);

  useEffect(() => {
    fetchAllPayments()
    fetchPaygoPayments()
    fetchCreditAdditions() // Fetch credit additions on mount
  }, []) // Add fetchCreditAdditions to dependencies

  const handlePaygoQuery = () => { // Renamed from handleQuery
    fetchPaygoPayments();
  }

  const handleCreditQuery = () => { // New query handler for credit additions
    fetchCreditAdditions();
  }

  const handlePaygoDownload = () => {
    const worksheet = XLSX.utils.json_to_sheet(paygoPayments);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Paygo Payments");
    XLSX.writeFile(workbook, "paygo-payments.xlsx");
  };

  const handleCreditDownload = () => {
    const worksheet = XLSX.utils.json_to_sheet(creditAdditions);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Credit Additions");
    XLSX.writeFile(workbook, "credit-additions.xlsx");
  };

  // Consolidated loading/error for initial render
  if (loading && loadingCredit) { // Check both loading states
    return <div>Loading...</div>
  }

  if (error || errorCredit) { // Check both error states
    return <div>Error: {error?.message || errorCredit}</div>
  }

  return (
    <Tabs defaultValue="paygo-payments">
      <TabsList>
        <TabsTrigger value="paygo-payments">Paygo Payments</TabsTrigger>
        <TabsTrigger value="all-payments">All Payments</TabsTrigger>
        <TabsTrigger value="credit-additions">Credit Additions</TabsTrigger> {/* New Tab Trigger */}
      </TabsList>
      <TabsContent value="paygo-payments">
        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader>
            <CardTitle>Paygo Payments</CardTitle>
            <CardDescription>A list of all paygo payments recorded in the system.</CardDescription>
            <div className="flex items-center space-x-2">
              <Input type="date" value={paygoFromDate} onChange={(e) => setPaygoFromDate(e.target.value)} />
              <Input type="date" value={paygoToDate} onChange={(e) => setPaygoToDate(e.target.value)} />
              <Button onClick={handlePaygoQuery}>Query</Button>
              <Button variant="outline" size="sm" onClick={handlePaygoDownload}>
                <Download className="mr-2 h-4 w-4" />
                Download
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader className="bg-gray-100">
                <TableRow>
                  <TableHead>Customer</TableHead>
                  <TableHead>Amount</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>Transaction ID</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody className="text-blue-900">
                {paygoPayments.length > 0 && paygoPayments?.map((payment) => (
                  <TableRow key={payment?.transactionId} className="hover:bg-gray-100 even:bg-gray-50">
                    <TableCell className="font-medium text-blue-900">{payment?.customerName}</TableCell>
                    <TableCell>{payment.currency} {payment.amount.toLocaleString()}</TableCell>
                    <TableCell>{payment.transactionType}</TableCell>
                    <TableCell>{new Date(payment.timestamp).toLocaleDateString()}</TableCell>
                    <TableCell>{payment.transactionId}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </TabsContent>
      <TabsContent value="all-payments">
        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader>
            <CardTitle>All Payments</CardTitle>
            <CardDescription>A list of all payments recorded in the system.</CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader className="bg-gray-100">
                <TableRow>
                  <TableHead>Customer</TableHead>
                  <TableHead>Amount</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Method</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>Transaction ID</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody className="text-blue-900">
                {allPayments.length > 0 && allPayments?.map((payment) => (
                  <TableRow key={payment?.id} className="hover:bg-gray-100 even:bg-gray-50">
                    <TableCell className="font-medium text-blue-900">{payment?.customer}</TableCell>
                    <TableCell>NGN {payment.amount.toLocaleString()}</TableCell>
                    <TableCell>
                      <Badge variant={payment.status === "completed" ? "success" : "destructive"}>
                        {payment.status}
                      </Badge>
                    </TableCell>
                    <TableCell>{payment.payment_method}</TableCell>
                    <TableCell>{new Date(payment.payment_date).toLocaleDateString()}</TableCell>
                    <TableCell>{payment.transaction_id}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </TabsContent>
      {/* New TabsContent for Credit Additions */}
      <TabsContent value="credit-additions">
        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader>
            <CardTitle>Credit Additions</CardTitle>
            <CardDescription>A list of all credit additions recorded in the system.</CardDescription>
            <div className="flex items-center space-x-2">
              <Input type="date" value={creditFromDate} onChange={(e) => setCreditFromDate(e.target.value)} />
              <Input type="date" value={creditToDate} onChange={(e) => setCreditToDate(e.target.value)} />
              <Button onClick={handleCreditQuery}>Query</Button>
              <Button variant="outline" size="sm" onClick={handleCreditDownload}>
                <Download className="mr-2 h-4 w-4" />
                Download
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {loadingCredit && <p>Loading credit additions...</p>}
            {errorCredit && <p className="text-red-500">{errorCredit}</p>}
            {!loadingCredit && !errorCredit && (
              <Table>
                <TableHeader className="bg-gray-100">
                  <TableRow>
                    <TableHead>Agent Name</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Added By</TableHead>
                    <TableHead>Description</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody className="text-blue-900">
                  {creditAdditions.length > 0 ? (
                    creditAdditions.map((addition) => (
                      <TableRow key={addition.transaction_id} className="hover:bg-gray-100 even:bg-gray-50">
                        <TableCell className="font-medium text-blue-900">{addition.agent_name}</TableCell>
                        <TableCell>NGN {parseFloat(addition.credit_amount).toLocaleString()}</TableCell>
                        <TableCell>{new Date(addition.transaction_date).toLocaleDateString()}</TableCell>
                        <TableCell>{addition.admin_name}</TableCell>
                        <TableCell>{addition.description}</TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center">No credit additions found for the selected date range.</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </TabsContent>
    </Tabs>
  )
}
