"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { IconCurrency } from "@tabler/icons-react"
import { Button } from "@/components/ui/button"
import { DataTableContracts } from "@/components/data-table-contracts"
import { ColumnDef } from "@tanstack/react-table"
import balancestatementData from '../api/balancestatementdata.json'
import partnersData from '../api/partnersdata.json'
import { Calendar } from "@/components/ui/calendar"
import { format } from "date-fns"
import { CalendarIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ChartBalanceStatement } from "@/components/chart-balance-statement"

type ImportedTransaction = {
  id: number;
  transactionDate: string;
  debitAmount: string;
  creditAmount: string;
  operationNumber: string;
  cif: string;
  description: string;
  currency: string;
  notes?: string;
  partnerName?: string;
}

type ChartData = {
  date: string;
  debit: number;
  credit: number;
}

export default function BalanceStatementPage() {
  const [dateRange, setDateRange] = useState<{
    from: Date | undefined;
    to: Date | undefined;
  }>(() => {
    const today = new Date()
    const oneMonthAgo = new Date()
    oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1)
    return {
      from: oneMonthAgo,
      to: today,
    }
  })
  const [transactions, setTransactions] = useState<ImportedTransaction[]>([])
  const [selectedCurrency, setSelectedCurrency] = useState<'RON' | 'EUR'>('RON')
  const { t } = useTranslation()

  useEffect(() => {
    // Filter transactions based on date range and currency
    if (dateRange.from && dateRange.to) {
      const filtered = balancestatementData
        .filter(transaction => {
          // Handle different date formats
          let transactionDate: Date
          if (transaction.transactionDate.includes('/')) {
            const [day, month, year] = transaction.transactionDate.split('/')
            transactionDate = new Date(`${year}-${month}-${day}`)
          } else {
            transactionDate = new Date(transaction.transactionDate)
          }
          const matchesDate = transactionDate >= dateRange.from! && transactionDate <= dateRange.to!
          const matchesCurrency = transaction.currency === selectedCurrency
          return matchesDate && matchesCurrency
        })
        .map((transaction, index) => {
          // Handle different date formats for display
          let formattedDate: string
          if (transaction.transactionDate.includes('/')) {
            const [day, month, year] = transaction.transactionDate.split('/')
            formattedDate = `${year}-${month}-${day}`
          } else {
            formattedDate = transaction.transactionDate
          }

          // Find partner name based on CIF
          const partner = partnersData.find(p => 
            p.bankAccounts?.some(account => account.iban === transaction.cif)
          )

          return {
            ...transaction,
            id: index + 1,
            transactionDate: formattedDate,
            debitAmount: transaction.debitAmount ? String(transaction.debitAmount) : '',
            creditAmount: transaction.creditAmount ? String(transaction.creditAmount) : '',
            operationNumber: transaction.operationNumber || '',
            cif: transaction.cif || '',
            description: transaction.description || '',
            currency: transaction.currency || '',
            partnerName: partner?.companyName || '',
          }
        })
      setTransactions(filtered)
    }
  }, [dateRange, selectedCurrency])

  // Calculate totals for summary cards based on filtered transactions
  const totalIncome = transactions.reduce((sum, t) => {
    const credit = parseFloat(t.creditAmount) || 0
    return sum + credit
  }, 0)

  const totalExpenses = transactions.reduce((sum, t) => {
    const debit = parseFloat(t.debitAmount) || 0
    return sum + debit
  }, 0)

  const netBalance = totalIncome - totalExpenses
  const changePercentage = totalExpenses !== 0 ? (netBalance / totalExpenses) * 100 : 0

  // Transform transactions data for the chart
  const chartData: ChartData[] = transactions.map(t => {
    const debit = parseFloat(t.debitAmount.replace(/,/g, '')) || 0;
    const credit = parseFloat(t.creditAmount.replace(/,/g, '')) || 0;
    return {
      date: t.transactionDate,
      debit,
      credit
    };
  }).sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

  console.log('Chart Data:', chartData);

  const importedColumns: ColumnDef<ImportedTransaction>[] = [
    { accessorKey: 'transactionDate', header: 'Transaction Date' },
    { accessorKey: 'partnerName', header: 'Company' },
    { accessorKey: 'debitAmount', header: 'Debit Amount' },
    { accessorKey: 'creditAmount', header: 'Credit Amount' },
    { accessorKey: 'operationNumber', header: 'Operation Number' },
    { accessorKey: 'cif', header: 'CIF' },
    {
      accessorKey: 'description',
      header: 'Description',
      cell: ({ row }) => {
        const description = row.original.description
        return (
          <span className="max-w-[200px] truncate" title={description}>
            {description.length > 20 ? `${description.substring(0, 20)}...` : description}
          </span>
        )
      }
    },
    { accessorKey: 'currency', header: 'Currency' }
  ]

  const summary = {
    totalIncome,
    totalExpenses,
    netBalance,
    changePercentage,
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
              <div className="px-4 lg:px-6">
                <div className="flex justify-between items-center mb-6">
                  <h2 className="text-2xl font-bold">{t("balanceStatement.title")}</h2>
                  <div className="flex items-center gap-4">
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button
                          id="date"
                          variant={"outline"}
                          className={cn(
                            "w-[300px] justify-start text-left font-normal",
                            !dateRange.from && "text-muted-foreground"
                          )}
                        >
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {dateRange?.from ? (
                            dateRange.to ? (
                              <>
                                {format(dateRange.from, "LLL dd, y")} -{" "}
                                {format(dateRange.to, "LLL dd, y")}
                              </>
                            ) : (
                              format(dateRange.from, "LLL dd, y")
                            )
                          ) : (
                            <span>Pick a date range</span>
                          )}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0" align="start">
                        <Calendar
                          initialFocus
                          mode="range"
                          defaultMonth={dateRange?.from}
                          selected={dateRange}
                          onSelect={(range) => {
                            if (range) {
                              setDateRange({
                                from: range.from,
                                to: range.to,
                              })
                            }
                          }}
                          numberOfMonths={2}
                        />
                      </PopoverContent>
                    </Popover>
                    <DropdownMenu>
                      <DropdownMenuTrigger >
                        <Button variant="outline">
                          <IconCurrency className="h-4 w-4 mr-2"/>
                          {t(`${selectedCurrency}`)}
                        </Button>
                        <DropdownMenuContent>
                          <DropdownMenuItem onClick={() => setSelectedCurrency('RON')}>RON</DropdownMenuItem>
                          <DropdownMenuItem onClick={() => setSelectedCurrency('EUR')}>EUR</DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenuTrigger>
                    </DropdownMenu>
                  </div>
                </div>

                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
                  <Card>
                    <CardHeader>
                      <CardTitle>Total Income</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">{summary.totalIncome.toFixed(2)} {selectedCurrency}</div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader>
                      <CardTitle>Total Expenses</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold text-red-600">{summary.totalExpenses.toFixed(2)} {selectedCurrency}</div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader>
                      <CardTitle>Net Balance</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold text-green-600">{summary.netBalance.toFixed(2)} {selectedCurrency}</div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader>
                      <CardTitle>Change</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center">
                        <span className={summary.changePercentage >= 0 ? "text-green-600" : "text-red-600"}>
                          {summary.changePercentage >= 0 ? "+" : ""}{summary.changePercentage.toFixed(2)}%
                        </span>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                <div className="mb-6">
                  <ChartBalanceStatement data={chartData} />
                </div>

                <Card>
                  <CardHeader>
                    <CardTitle>Imported Transactions</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <DataTableContracts data={transactions} columns={importedColumns} />
                  </CardContent>
                </Card>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
}
