import { useState } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  IconButton,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from '@mui/material';
import { ArrowBack } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { buchhaltungApi } from '../services/buchhaltung';
import { TRANSAKTION_TYP_LABELS } from '../types/buchhaltung.types';
import type { BankkontoStatementRow } from '../types/buchhaltung.types';

function fmtEur(val: number) {
  return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(val);
}

function fmtDate(val: string) {
  return new Date(val).toLocaleDateString('de-DE');
}

export default function BuchhaltungBankkontoDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const bankkontoId = Number(id);

  const [von, setVon] = useState('');
  const [bis, setBis] = useState('');
  const [appliedVon, setAppliedVon] = useState('');
  const [appliedBis, setAppliedBis] = useState('');

  const { data, isLoading, isError } = useQuery({
    queryKey: ['bankkonto-statement', bankkontoId, appliedVon, appliedBis],
    queryFn: () => buchhaltungApi.getBankkontoStatement(bankkontoId, {
      von: appliedVon || undefined,
      bis: appliedBis || undefined,
    }),
    enabled: !!bankkontoId,
  });

  const handleApply = () => {
    setAppliedVon(von);
    setAppliedBis(bis);
  };

  return (
    <DashboardLayout>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
        <Tooltip title="Zurueck">
          <IconButton onClick={() => navigate('/buchhaltung?tab=2')}>
            <ArrowBack />
          </IconButton>
        </Tooltip>
        <Typography variant="h4" sx={{ flexGrow: 1 }}>
          {data?.bankkonto?.bezeichnung ?? 'Bankkonto'}
          {data?.bankkonto?.iban && (
            <Typography component="span" variant="body1" color="text.secondary" sx={{ ml: 2 }}>
              {data.bankkonto.iban}
            </Typography>
          )}
        </Typography>
      </Box>

      {/* Date range filter */}
      <Paper variant="outlined" sx={{ p: 1.5, mb: 3 }}>
        <Stack direction="row" spacing={2} alignItems="center">
          <TextField
            size="small"
            label="Von"
            type="date"
            value={von}
            onChange={e => setVon(e.target.value)}
            InputLabelProps={{ shrink: true }}
          />
          <TextField
            size="small"
            label="Bis"
            type="date"
            value={bis}
            onChange={e => setBis(e.target.value)}
            InputLabelProps={{ shrink: true }}
          />
          <Button variant="contained" size="small" onClick={handleApply}>
            Anwenden
          </Button>
        </Stack>
      </Paper>

      {isLoading && <CircularProgress />}
      {isError && <Typography color="error">Fehler beim Laden der Kontodaten.</Typography>}

      {data && !isLoading && (
        <>
          {/* Summary cards */}
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 2, mb: 3 }}>
            <Card>
              <CardContent>
                <Typography color="text.secondary" variant="body2">Einnahmen</Typography>
                <Typography variant="h5" color="success.main">{fmtEur(data.einnahmen)}</Typography>
              </CardContent>
            </Card>
            <Card>
              <CardContent>
                <Typography color="text.secondary" variant="body2">Ausgaben</Typography>
                <Typography variant="h5" color="error.main">{fmtEur(data.ausgaben)}</Typography>
              </CardContent>
            </Card>
            <Card>
              <CardContent>
                <Typography color="text.secondary" variant="body2">Saldo</Typography>
                <Typography variant="h5" color={data.saldo >= 0 ? 'success.main' : 'error.main'}>{fmtEur(data.saldo)}</Typography>
              </CardContent>
            </Card>
          </Box>

          {/* Statement table */}
          <TableContainer component={Paper}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Datum</TableCell>
                  <TableCell>Typ</TableCell>
                  <TableCell>Beschreibung</TableCell>
                  <TableCell>Beleg-Nr.</TableCell>
                  <TableCell align="right">Betrag</TableCell>
                  <TableCell align="right">Laufender Saldo</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {data.rows.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={6} align="center">
                      <Typography color="text.secondary">Keine Transaktionen im Zeitraum</Typography>
                    </TableCell>
                  </TableRow>
                )}
                {data.rows.map((row: BankkontoStatementRow) => {
                  const isEinnahme = row.typ === 'einnahme';
                  const isTransfer = row.typ === 'transfer';
                  return (
                    <TableRow key={row.id} hover>
                      <TableCell>{fmtDate(row.datum)}</TableCell>
                      <TableCell>
                        <Chip
                          label={isTransfer ? `Transfer${row.transfer_ziel_bezeichnung ? ' \u2192 ' + row.transfer_ziel_bezeichnung : ''}` : TRANSAKTION_TYP_LABELS[row.typ]}
                          size="small"
                          color={isEinnahme ? 'success' : isTransfer ? 'info' : 'error'}
                        />
                      </TableCell>
                      <TableCell>{row.beschreibung || '\u2013'}</TableCell>
                      <TableCell>{row.beleg_nr || '\u2013'}</TableCell>
                      <TableCell
                        align="right"
                        sx={{
                          color: isEinnahme ? 'success.main' : isTransfer ? 'info.main' : 'error.main',
                          fontWeight: 600,
                        }}
                      >
                        {row.typ === 'ausgabe' ? '-' : row.typ === 'einnahme' ? '+' : ''}{fmtEur(row.betrag)}
                      </TableCell>
                      <TableCell align="right" sx={{ fontWeight: 600 }}>
                        {fmtEur(row.laufender_saldo)}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        </>
      )}
    </DashboardLayout>
  );
}
