"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useState, useCallback } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { IconUpload } from "@tabler/icons-react"
import { DataTableSimple } from "@/components/data-table-simple"
import { ColumnDef } from "@tanstack/react-table"
import { Input } from "@/components/ui/input"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import * as XLSX from 'xlsx'
import { Label } from "@/components/ui/label"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

type BankTransaction = {
  transactionDate: string
  debitAmount: number | string
  creditAmount: number | string
  operationNumber: string
  cif: string
  iban: string
  description: string
  currency: string
}

// Add a list of possible header keywords for detection
const HEADER_KEYWORDS = {
  transactionDate: ['data tranzactiei', 'data', 'date', 'transaction date'],
  debitAmount: ['suma debit', 'debit', 'debit amount'],
  creditAmount: ['suma credit', 'credit', 'credit amount'],
  operationNumber: ['nr. document', 'operation', 'operation number'],
  cif: ['cod fiscal', 'cif', 'fiscal code'],
  iban: ['iban', 'account number'],
  description: ['descriere', 'description', 'beneficiar'],
  currency: ['valuta', 'currency']
}

// Helper to find the real header row index
function findHeaderRowIndex(rows: string[][]): number {
  for (let i = 0; i < rows.length; i++) {
    const row = rows[i].map(cell => String(cell || '').toLowerCase().trim())
    // Count how many keywords are present in this row
    const matchCount = Object.values(HEADER_KEYWORDS).flat().filter(keyword => 
      row.some(cell => cell.includes(keyword))
    ).length
    if (matchCount >= 3) {
      return i
    }
  }
  return 0 // fallback to first row
}

// Helper to map headers to our fields
function mapHeaders(headers: string[]): Record<keyof BankTransaction, string> {
  const mapping: Record<keyof BankTransaction, string> = {
    transactionDate: '',
    debitAmount: '',
    creditAmount: '',
    operationNumber: '',
    cif: '',
    iban: '',
    description: '',
    currency: ''
  }

  headers.forEach(header => {
    const headerLower = header.toLowerCase()
    for (const [field, keywords] of Object.entries(HEADER_KEYWORDS)) {
      if (keywords.some(keyword => headerLower.includes(keyword))) {
        mapping[field as keyof BankTransaction] = header
        break
      }
    }
  })

  return mapping
}

export default function BankImportPage() {
  const { t } = useTranslation()
  const [transactions, setTransactions] = useState<BankTransaction[]>([])
  const [showManualInput, setShowManualInput] = useState(false)
  const [saving, setSaving] = useState(false)
  const [saveMessage, setSaveMessage] = useState<string | null>(null)
  const [manualTransaction, setManualTransaction] = useState<BankTransaction>({
    transactionDate: '',
    debitAmount: '',
    creditAmount: '',
    operationNumber: '',
    cif: '',
    iban: '',
    description: '',
    currency: 'RON',
  })

  const handleFileProcess = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    const fileExtension = file.name.split('.').pop()?.toLowerCase()
    const reader = new FileReader()

    reader.onload = (e) => {
      let allRows: string[][] = []
      if (fileExtension === 'csv') {
        const text = e.target?.result as string
        allRows = text.split('\n').map(line => line.split(',').map(v => v.trim()))
      } else if (fileExtension === 'xlsx') {
        const data = new Uint8Array(e.target?.result as ArrayBuffer)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        allRows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as string[][]
      }

      // Find the real header row
      const headerRowIdx = findHeaderRowIndex(allRows)
      const headers = (allRows[headerRowIdx] || []).map(h => (h || '').toString().trim())
      const dataRows = allRows.slice(headerRowIdx + 1)
      
      // Map headers to our fields
      const headerMapping = mapHeaders(headers)
      
      // Process data rows
      const newTransactions = dataRows
        .map(row => {
          const getValue = (field: keyof BankTransaction) => {
            const header = headerMapping[field]
            if (!header) return ''
            const index = headers.indexOf(header)
            return index >= 0 ? row[index] : ''
          }

          return {
            transactionDate: getValue('transactionDate'),
            debitAmount: getValue('debitAmount'),
            creditAmount: getValue('creditAmount'),
            operationNumber: getValue('operationNumber'),
            cif: getValue('cif'),
            iban: getValue('iban'),
            description: getValue('description'),
            currency: getValue('currency') || 'RON',
          }
        })
        .filter(transaction => transaction.transactionDate && transaction.transactionDate.trim() !== '')

      setTransactions(newTransactions)
    }

    if (fileExtension === 'csv') {
      reader.readAsText(file)
    } else if (fileExtension === 'xlsx') {
      reader.readAsArrayBuffer(file)
    }
  }, [])

  const handleManualInput = () => {
    setTransactions(prev => [...prev, manualTransaction])
    setManualTransaction({
      transactionDate: '',
      debitAmount: '',
      creditAmount: '',
      operationNumber: '',
      cif: '',
      iban: '',
      description: '',
      currency: 'RON',
    })
    setShowManualInput(false)
  }

  const columns: ColumnDef<BankTransaction>[] = [
    { accessorKey: "transactionDate", header: "Transaction Date" },
    { accessorKey: "debitAmount", header: "Debit Amount" },
    { accessorKey: "creditAmount", header: "Credit Amount" },
    { accessorKey: "operationNumber", header: "Operation Number" },
    { accessorKey: "cif", header: "CIF" },
    { accessorKey: "iban", header: "IBAN" },
    {
      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 handleSave = async () => {
    setSaving(true)
    setSaveMessage(null)
    try {
      const res = await fetch('/api/balancestatement', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(transactions),
      })
      if (res.ok) {
        setSaveMessage('Saved to balance statement!')
        setTransactions([])
      } else {
        setSaveMessage('Error saving data!')
      }
    } catch (e) {
      setSaveMessage('Error saving data!')
    }
    setSaving(false)
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader title="Bank Import" />
        <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="flex justify-between items-center px-4 lg:px-6">
                <h2 className="text-2xl font-bold">Bank Import</h2>
                <Button onClick={() => setShowManualInput(true)}>Add Manual Transaction</Button>
              </div>

              {/* File Upload Card */}
              <Card className="mx-4 lg:mx-6 max-w-2xl w-full self-center">
                <CardHeader>
                  <CardTitle>Import Bank Statement</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center gap-4">
                    <div className="w-full">
                      <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center bg-muted">
                        <input
                          type="file"
                          id="file-upload"
                          className="hidden"
                          accept=".csv,.xlsx"
                          onChange={handleFileProcess}
                        />
                        <label
                          htmlFor="file-upload"
                          className="cursor-pointer flex flex-col items-center gap-2"
                        >
                          <IconUpload className="h-8 w-8 text-gray-400" />
                          <span className="text-sm text-gray-600">
                            Drag and drop your file here, or click to browse
                          </span>
                          <span className="text-xs text-gray-500">
                            Supported formats: CSV, Excel
                          </span>
                        </label>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Imported Transactions Table */}
              {transactions.length > 0 && (
                <Card className="mx-4 lg:mx-6">
                  <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle>Imported Transactions</CardTitle>
                    <Button onClick={handleSave} variant="default" disabled={saving}>{saving ? 'Saving...' : 'Save'}</Button>
                  </CardHeader>
                  <CardContent>
                    <DataTableSimple columns={columns} data={transactions} />
                  </CardContent>
                </Card>
              )}

              {saveMessage && <div className="text-sm mt-2 text-center text-green-600">{saveMessage}</div>}
            </div>
          </div>
        </div>
      </SidebarInset>

      {/* Manual Input Dialog */}
      <Dialog open={showManualInput} onOpenChange={setShowManualInput}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Add Manual Transaction</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="date" className="text-right">Date</Label>
              <Input
                id="date"
                type="date"
                className="col-span-3"
                value={manualTransaction.transactionDate}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, transactionDate: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="debit" className="text-right">Debit Amount</Label>
              <Input
                id="debit"
                type="number"
                className="col-span-3"
                value={manualTransaction.debitAmount}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, debitAmount: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="credit" className="text-right">Credit Amount</Label>
              <Input
                id="credit"
                type="number"
                className="col-span-3"
                value={manualTransaction.creditAmount}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, creditAmount: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="operation" className="text-right">Operation Number</Label>
              <Input
                id="operation"
                className="col-span-3"
                value={manualTransaction.operationNumber}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, operationNumber: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="cif" className="text-right">CIF</Label>
              <Input
                id="cif"
                className="col-span-3"
                value={manualTransaction.cif}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, cif: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="iban" className="text-right">IBAN</Label>
              <Input
                id="iban"
                className="col-span-3"
                value={manualTransaction.iban}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, iban: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="description" className="text-right">Description</Label>
              <Input
                id="description"
                className="col-span-3"
                value={manualTransaction.description}
                onChange={(e) => setManualTransaction(prev => ({ ...prev, description: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="currency" className="text-right">Currency</Label>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" className="w-full justify-start">
                    {manualTransaction.currency || 'RON'}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  <DropdownMenuItem onClick={() => setManualTransaction({ ...manualTransaction, currency: 'RON' })}>RON</DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setManualTransaction({ ...manualTransaction, currency: 'EUR' })}>EUR</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
          <div className="flex justify-end gap-4">
            <Button variant="outline" onClick={() => setShowManualInput(false)}>
              Cancel
            </Button>
            <Button onClick={handleManualInput}>
              Add Transaction
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </SidebarProvider>
  )
}