"use client"

import { useState, useEffect, useCallback } from "react"
import { CommissionsList } from "@/components/commissions-list"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input" // Import Input
import { Button } from "@/components/ui/button" // Import Button
import { getAgentCommissions, getSuperAgentCommissions } from "@/services/api"
import * as XLSX from "xlsx"; // Import XLSX
import { Download } from 'lucide-react'; // Import Download icon

// 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 CommissionsPage() {
  const [userRole, setUserRole] = useState(null) // Will be determined by auth
  const [commissions, setCommissions] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);

  useEffect(() => {
    // Simulate fetching user role from auth data
    const authData = localStorage.getItem("auth")
    if (authData) {
      const parsedData = JSON.parse(authData)
      // Assuming 'role' is part of the auth data, e.g., 'agent' or 'super-agent'
      // For now, we'll default to 'agent' if not specified or if no auth data
      setUserRole(parsedData.role || "agent")
    } else {
      setUserRole("agent") // Default role if no auth data
    }

    // Set default date range on initial load
    const defaultRange = getDefaultDateRange();
    setStartDate(defaultRange.startDate);
    setEndDate(defaultRange.endDate);
  }, [])

  const fetchCommissions = useCallback(async () => {
    if (!userRole || !startDate || !endDate) return // Wait for userRole and dates to be set

    setLoading(true)
    setError(null)
    try {
      let data = []
      if (userRole === "super-agent") {
        data = await getSuperAgentCommissions(startDate, endDate)
      } else {
        data = await getAgentCommissions(startDate, endDate)
      }
      setCommissions(data)
    } catch (err) {
      setError("Failed to fetch commissions.")
      console.error(err)
    } finally {
      setLoading(false)
    }
  }, [userRole, startDate, endDate])

  useEffect(() => {
    fetchCommissions()
  }, [fetchCommissions])

  const handleCommissionQuery = () => {
    fetchCommissions();
  };

  const handleCommissionDownload = () => {
    const worksheet = XLSX.utils.json_to_sheet(commissions);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Commissions");
    XLSX.writeFile(workbook, "commissions.xlsx");
  };

  return (
    <div className="flex-1 space-y-4 p-8 pt-6">
      <div className="flex items-center justify-between space-y-2">
        <h2 className="text-3xl font-bold tracking-tight">Commissions</h2>
      </div>
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>{userRole === "super-agent" ? "Super Agent Commissions" : "Agent Commissions"}</CardTitle>
            <div className="flex items-center space-x-2">
              <Input type="date" value={startDate || ''} onChange={(e) => setStartDate(e.target.value)} />
              <Input type="date" value={endDate || ''} onChange={(e) => setEndDate(e.target.value)} />
              <Button onClick={handleCommissionQuery}>Query</Button>
              <Button variant="outline" size="sm" onClick={handleCommissionDownload}>
                <Download className="mr-2 h-4 w-4" />
                Download
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {loading && <p>Loading commissions...</p>}
          {error && <p className="text-red-500">{error}</p>}
          {!loading && !error && (
            <CommissionsList commissions={commissions} userRole={userRole} />
          )}
        </CardContent>
      </Card>
    </div>
  )
}
