import { useCallback } from 'react';
// @mui
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Table from '@mui/material/Table';
import Stack from '@mui/material/Stack';
import Divider from '@mui/material/Divider';
import TableRow from '@mui/material/TableRow';
import TableHead from '@mui/material/TableHead';
import TableCell from '@mui/material/TableCell';
import TableBody from '@mui/material/TableBody';
import Grid from '@mui/material/Unstable_Grid2';
import Typography from '@mui/material/Typography';
import TableContainer from '@mui/material/TableContainer';
// utils
import { fDate } from 'src/utils/format-time';
import { fCurrency } from 'src/utils/format-number';
// types
import { Invoice } from 'src/schemas';
// components
import Label from 'src/components/label';
import Scrollbar from 'src/components/scrollbar';
//
import { mutate } from 'swr';
import { collections, updateDocument } from 'src/lib/firestore';
import { createFullAddress } from 'src/utils/create-full-address';
import { getQuantityType } from 'src/utils/get-invoice-quantity-type';
import InvoiceToolbar from './invoice-toolbar';
import { updateInvoice } from 'src/api/invoice';

// ----------------------------------------------------------------------

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '& td': {
    textAlign: 'right',
    borderBottom: 'none',
    paddingTop: theme.spacing(1),
    paddingBottom: theme.spacing(1),
  },
}));

// ----------------------------------------------------------------------

type Props = {
  invoice: Invoice;
};

export const INVOICE_STATUS_OPTIONS = [
  { value: 'draft', label: 'Draft' },
  // { value: 'processing', label: 'Processing' },
  { value: 'paid', label: 'Paid' },
  { value: 'pending', label: 'Pending' },
  { value: 'overdue', label: 'Overdue' },
];

export default function InvoiceDetails({ invoice }: Props) {
  const currentStatus = invoice.status;

  const handleChangeStatus = useCallback(
    async (event: React.ChangeEvent<HTMLInputElement>) => {
      // await updateDocument(collections.invoice, invoice.id, { status: event.target.value });
      await updateInvoice(invoice.id, {
        status: event.target.value as 'draft' | 'processing' | 'pending' | 'overdue' | 'paid',
      });
      mutate([collections.invoice, invoice.id]);
    },
    [invoice]
  );

  const renderTotal = (
    <>
      <StyledTableRow>
        <TableCell colSpan={4} />

        <TableCell sx={{ color: 'text.secondary' }}>
          <Box sx={{ mt: 2 }} />
          Subtotal
        </TableCell>
        <TableCell width={120} sx={{ typography: 'subtitle2' }}>
          <Box sx={{ mt: 2 }} />
          {fCurrency(invoice.subTotal, invoice.currency)}
        </TableCell>
      </StyledTableRow>

      {!!invoice.discount && (
        <StyledTableRow>
          <TableCell colSpan={4} />
          <TableCell sx={{ color: 'text.secondary' }}>Discount</TableCell>
          <TableCell width={120} sx={{ color: 'error.main', typography: 'body2' }}>
            {fCurrency(-invoice.discount, invoice.currency)}
          </TableCell>
        </StyledTableRow>
      )}

      {/* <StyledTableRow>
        <TableCell colSpan={3} />
        <TableCell sx={{ color: 'text.secondary' }}>Taxes</TableCell>
        <TableCell width={120}>{fCurrency(invoice.taxes)}</TableCell>
      </StyledTableRow> */}

      <StyledTableRow>
        <TableCell colSpan={4} />
        <TableCell sx={{ typography: 'subtitle1' }}>Total</TableCell>
        <TableCell width={140} sx={{ typography: 'subtitle1' }}>
          {fCurrency(invoice.totalAmount, invoice.currency)}
        </TableCell>
      </StyledTableRow>
    </>
  );

  const renderFooter = (
    <Grid container>
      <Grid xs={12} md={9} sx={{ py: 3 }}>
        <Typography variant="subtitle2">NOTES</Typography>

        <Typography variant="body2">
          VAT is not calculated according to article 14, paragraph 3, point 5 from the VAT act.
        </Typography>
      </Grid>

      <Grid xs={12} md={3} sx={{ py: 3, textAlign: 'right' }}>
        <Typography variant="subtitle2">Have a Question?</Typography>

        <Typography variant="body2">{invoice.invoiceFrom.email}</Typography>
      </Grid>
    </Grid>
  );

  const renderList = (
    <TableContainer sx={{ overflow: 'unset', mt: 5 }}>
      <Scrollbar>
        <Table sx={{ minWidth: 960 }}>
          <TableHead>
            <TableRow>
              <TableCell width={40}>#</TableCell>

              <TableCell sx={{ typography: 'subtitle2' }}>Description</TableCell>

              <TableCell align="right">{getQuantityType(invoice)}</TableCell>

              <TableCell align="right">Currency</TableCell>

              <TableCell align="right">Unit price</TableCell>

              <TableCell align="right">Total</TableCell>
            </TableRow>
          </TableHead>

          <TableBody>
            {invoice.items.map((row, index) => (
              <TableRow key={index}>
                <TableCell>{index + 1}</TableCell>

                <TableCell>
                  <Box sx={{ maxWidth: 560 }}>
                    <Typography variant="subtitle2">{row.title}</Typography>

                    <Typography variant="body2" sx={{ color: 'text.secondary' }} noWrap>
                      {row.description}
                    </Typography>
                  </Box>
                </TableCell>

                <TableCell align="right">{row.quantity}</TableCell>

                <TableCell align="right">{invoice.currency}</TableCell>

                <TableCell align="right">{fCurrency(row.price, invoice.currency)}</TableCell>

                <TableCell align="right">
                  {fCurrency(row.price * row.quantity, invoice.currency)}
                </TableCell>
              </TableRow>
            ))}

            {renderTotal}
          </TableBody>
        </Table>
      </Scrollbar>
    </TableContainer>
  );

  return (
    <>
      <InvoiceToolbar
        invoice={invoice}
        currentStatus={currentStatus || ''}
        onChangeStatus={handleChangeStatus}
        statusOptions={INVOICE_STATUS_OPTIONS}
      />

      <Card sx={{ pt: 5, px: 5 }}>
        <Box
          rowGap={5}
          display="grid"
          alignItems="center"
          gridTemplateColumns={{
            xs: 'repeat(1, 1fr)',
            sm: 'repeat(2, 1fr)',
          }}
        >
          <Box
            component="img"
            alt="logo"
            src="/logo/logo_single.svg"
            sx={{ width: 48, height: 48 }}
          />

          <Stack spacing={1} alignItems={{ xs: 'flex-start', md: 'flex-end' }}>
            <Label
              variant="soft"
              color={
                (currentStatus === 'paid' && 'success') ||
                (currentStatus === 'processing' && 'info') ||
                (currentStatus === 'pending' && 'warning') ||
                (currentStatus === 'overdue' && 'error') ||
                'default'
              }
            >
              {currentStatus}
            </Label>

            <Typography variant="h6">{invoice.invoiceNumber}</Typography>
          </Stack>

          <Stack sx={{ typography: 'body2', whiteSpace: 'pre-line' }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              Invoice From
            </Typography>
            {invoice.invoiceFrom.name}
            <br />
            {createFullAddress(invoice.invoiceFrom.address)}
            <br />
            <br />
            {invoice.invoiceFrom.email}
            <br />
          </Stack>

          <Stack sx={{ typography: 'body2', whiteSpace: 'pre-line' }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              Invoice To
            </Typography>
            {invoice.invoiceTo.name}
            <br />
            {!!invoice.invoiceTo.companyNumber && (
              <>
                Company ID: {invoice.invoiceTo.companyNumber}
                <br />
              </>
            )}
            {createFullAddress(invoice.invoiceTo.address)}
            <br />
            <br />
            {invoice.invoiceTo.email}
            <br />
          </Stack>

          <Stack sx={{ typography: 'body2' }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              Date Issued
            </Typography>
            {fDate(invoice.createDate)}
          </Stack>

          <Stack sx={{ typography: 'body2' }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              Due Date
            </Typography>
            {fDate(invoice.dueDate)}
          </Stack>
        </Box>

        {renderList}

        <Divider sx={{ mt: 5, borderStyle: 'dashed' }} />

        {renderFooter}
      </Card>
    </>
  );
}
