import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  Divider,
  LinearProgress,
} from '@mui/material';
import {
  Receipt as ReceiptIcon,
  Refresh as RefreshIcon,
  Description as DescriptionIcon,
  CheckCircle as CheckCircleIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import { apiJson, apiFetch } from '../lib/api';
import { logger } from '../lib/logger';

interface BillingRecord {
  id: number;
  subscription_id: number;
  customer_id: number;
  customer_name: string;
  period_start: string;
  period_end: string;
  calculated_amount: number;
  currency: string;
  invoice_status: string;
  created_at: string;
}

interface PricingConfig {
  id: number;
  name: string;
  metric_type: string;
  unit: string;
  rate_per_unit: number;
  currency: string;
  is_active: boolean;
}

interface BillingPreview {
  customer_name: string;
  period_start: string;
  period_end: string;
  line_items: Array<{
    description: string;
    quantity: number;
    unit: string;
    rate: number;
    amount: number;
  }>;
  subtotal: number;
  tax: number;
  total: number;
  currency: string;
}

const BillingPage: React.FC = () => {
  const { t } = useI18n();
  const [records, setRecords] = useState<BillingRecord[]>([]);
  const [pricing, setPricing] = useState<PricingConfig[]>([]);
  const [loading, setLoading] = useState(false);
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [billingPreview, setBillingPreview] = useState<BillingPreview | null>(null);

  useEffect(() => {
    fetchBilling();
    fetchPricing();
  }, []);

  const fetchBilling = async () => {
    setLoading(true);
    try {
      const data = await apiJson<BillingRecord[]>('/billing/records');
      setRecords(data);
    } catch (error) {
      logger.error('Failed to fetch billing records:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchPricing = async () => {
    try {
      const data = await apiJson<PricingConfig[]>('/pricing');
      setPricing(data);
    } catch (error) {
      logger.error('Failed to fetch pricing:', error);
    }
  };



  const handlePreview = async (recordId: number) => {
    try {
      const preview = await apiJson<BillingPreview>(`/billing/preview/${recordId}`);
      setBillingPreview(preview);
      setPreviewDialogOpen(true);
    } catch (error) {
      logger.error('Failed to fetch preview:', error);
    }
  };

  const handleSendToSAP = async (recordId: number) => {
    try {
      await apiFetch(`/billing/send-to-sap/${recordId}`, { method: 'POST' });
      fetchBilling();
    } catch (error) {
      logger.error('Failed to send to SAP:', error);
    }
  };

  const handleExport = async (recordId: number, format: 'pdf' | 'csv' | 'xlsx') => {
    try {
      const response = await apiFetch(`/reports/export/${format}?billing_id=${recordId}`, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      
      if (!response.ok) throw new Error('Export failed');
      
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `invoice-${recordId}.${format}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      logger.error('Failed to export:', error);
    }
  };

  const getStatusColor = (status: string): 'default' | 'error' | 'warning' | 'success' => {
    switch (status) {
      case 'draft': return 'default';
      case 'pending': return 'warning';
      case 'sent': return 'success';
      case 'synced': return 'success';
      case 'failed': return 'error';
      default: return 'default';
    }
  };

  const getStatusLabel = (status: string): string => {
    const statusLabels: Record<string, string> = {
      draft: t('billing.draft'),
      pending: t('billing.pending'),
      sent: t('billing.sent'),
      synced: t('billing.synced'),
      failed: t('billing.failed'),
    };
    return statusLabels[status] || status;
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4">{t('billing.title')}</Typography>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button 
            variant="outlined" 
            startIcon={<ReceiptIcon />}
            onClick={() => {
              // Open generate dialog
            }}
          >
            {t('billing.generate')}
          </Button>
          <Button 
            variant="contained" 
            startIcon={<RefreshIcon />}
            onClick={fetchBilling}
          >
            {t('billing.refresh')}
          </Button>
        </Box>
      </Box>

      {loading && <LinearProgress />}

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>{t('billing.pricingSummary')}</Typography>
          <Grid container spacing={2}>
            {pricing.map((p) => (
              <Grid item xs={12} md={6} lg={3} key={p.id}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="subtitle2" color="textSecondary">
                      {p.name}
                    </Typography>
                    <Typography variant="h6" sx={{ mt: 1 }}>
                      {p.rate_per_unit.toLocaleString()} {p.currency} / {p.unit}
                    </Typography>
                    <Typography variant="caption" color="textSecondary">
                      {p.metric_type.toUpperCase()}
                    </Typography>
                    <Chip 
                      label={p.is_active ? t('billing.active') : t('billing.inactive')} 
                      size="small"
                      color={p.is_active ? 'success' : 'default'}
                      sx={{ mt: 1 }}
                    />
                  </CardContent>
                </Card>
              </Grid>
            ))}
            {pricing.length === 0 && (
              <Grid item xs={12}>
                <Typography variant="body2" color="textSecondary">
                  {t('billing.noPricing')}
                </Typography>
              </Grid>
            )}
          </Grid>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            {t('billing.records')}
          </Typography>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>ID</TableCell>
                  <TableCell>{t('billing.customer')}</TableCell>
                  <TableCell>{t('billing.period')}</TableCell>
                  <TableCell align="right">{t('billing.amount')}</TableCell>
                  <TableCell>{t('billing.status')}</TableCell>
                  <TableCell>{t('billing.created')}</TableCell>
                  <TableCell>{t('billing.actions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {records.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} align="center">
                      <Typography variant="body2" color="textSecondary">
                        {t('billing.noRecords')}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ) : (
                  records.map((record) => (
                    <TableRow key={record.id}>
                      <TableCell>{record.id}</TableCell>
                      <TableCell>{record.customer_name}</TableCell>
                      <TableCell>
                        {new Date(record.period_start).toLocaleDateString()} - {new Date(record.period_end).toLocaleDateString()}
                      </TableCell>
                      <TableCell align="right">
                        {record.calculated_amount.toLocaleString()} {record.currency}
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={getStatusLabel(record.invoice_status)} 
                          color={getStatusColor(record.invoice_status)} 
                          size="small"
                        />
                      </TableCell>
                      <TableCell>
                        {new Date(record.created_at).toLocaleDateString()}
                      </TableCell>
                      <TableCell>
                        <Box sx={{ display: 'flex', gap: 0.5 }}>
                          <Button
                            size="small"
                            variant="outlined"
                            onClick={() => handlePreview(record.id)}
                            startIcon={<DescriptionIcon />}
                          >
                            {t('billing.preview')}
                          </Button>
                          {record.invoice_status === 'draft' && (
                            <Button
                              size="small"
                              variant="outlined"
                              onClick={() => handleSendToSAP(record.id)}
                              startIcon={<CheckCircleIcon />}
                            >
                              {t('billing.syncToSap')}
                            </Button>
                          )}
                          <Button
                            size="small"
                            variant="outlined"
                            onClick={() => handleExport(record.id, 'pdf')}
                          >
                            PDF
                          </Button>
                        </Box>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </CardContent>
      </Card>

      <Dialog open={previewDialogOpen} onClose={() => setPreviewDialogOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <DescriptionIcon />
            <Typography variant="h6">{t('billing.invoicePreview')}</Typography>
          </Box>
        </DialogTitle>
        <DialogContent>
          {billingPreview && (
            <Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                <Box>
                  <Typography variant="subtitle2" color="textSecondary">{t('billing.invoiceTo')}</Typography>
                  <Typography variant="h6">{billingPreview.customer_name}</Typography>
                </Box>
                <Box>
                  <Typography variant="subtitle2" color="textSecondary">{t('billing.period')}</Typography>
                  <Typography variant="h6">
                    {new Date(billingPreview.period_start).toLocaleDateString()} - {new Date(billingPreview.period_end).toLocaleDateString()}
                  </Typography>
                </Box>
              </Box>

              <Divider sx={{ my: 2 }} />

              <Box>
                {billingPreview.line_items.length > 0 ? (
                  billingPreview.line_items.map((item, index) => (
                    <Box key={index} sx={{ display: 'flex', justifyContent: 'space-between', py: 1 }}>
                      <Typography>{item.description}</Typography>
                      <Typography>{item.quantity} {item.unit} @ {item.rate} = {item.amount.toFixed(2)} {billingPreview.currency}</Typography>
                    </Box>
                  ))
                ) : (
                  <Typography variant="body2" color="textSecondary">{t('billing.noLineItems')}</Typography>
                )}
              </Box>

              <Divider sx={{ my: 2 }} />

              <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Box sx={{ width: 300 }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 1 }}>
                     <Typography variant="subtitle2">{t('billing.subtotal')}</Typography>
                    <Typography variant="subtitle2">{billingPreview.subtotal.toFixed(2)} {billingPreview.currency}</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 1 }}>
                     <Typography variant="subtitle2">{t('billing.tax')}</Typography>
                    <Typography variant="subtitle2">{billingPreview.tax.toFixed(2)} {billingPreview.currency}</Typography>
                  </Box>
                  <Divider sx={{ my: 1 }} />
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 1 }}>
                     <Typography variant="h6">{t('billing.total')}</Typography>
                    <Typography variant="h6">{billingPreview.total.toFixed(2)} {billingPreview.currency}</Typography>
                  </Box>
                </Box>
              </Box>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
           <Button onClick={() => setPreviewDialogOpen(false)}>{t('common.close')}</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default BillingPage;
