'use client';

import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  Font,
  pdf,
} from '@react-pdf/renderer';

import { formatDate, formatNumber } from '@/lib/helper';
import type { Uniformity } from '@/types/api/production/uniformity';

Font.register({
  family: 'Helvetica',
  src: 'helvetica',
});

const pdfStyles = StyleSheet.create({
  page: {
    fontSize: 10,
    fontFamily: 'Helvetica',
    padding: 20,
    backgroundColor: '#FFFFFF',
  },
  titleSection: {
    marginBottom: 10,
  },
  mainTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 5,
    color: '#1f74bf',
  },
  table: {
    borderWidth: 1,
    borderColor: '#000000',
    marginBottom: 15,
  },
  tableRow: {
    flexDirection: 'row',
  },
  tableHeader: {
    backgroundColor: '#F5F5F5',
  },
  tableCell: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'left',
  },
  tableCellHeader: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
    textAlign: 'center',
  },
  tableCellHeaderRight: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    textAlign: 'right',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
  },
  tableCellRight: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'right',
  },
  tableCellCenter: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 8,
    textAlign: 'center',
  },
  tableBorderBottom: {
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
  },
  badge: {
    backgroundColor: '#1f74bf',
    color: '#FFFFFF',
    padding: 2,
    borderRadius: 2,
    fontSize: 7,
    fontWeight: 'bold',
    alignSelf: 'center',
  },
  parameterBadge: {
    backgroundColor: '#F5F5F5',
    color: '#333333',
    padding: 4,
    borderRadius: 4,
    fontSize: 8,
    marginRight: 8,
    marginBottom: 4,
  },
  parameterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
  },
});

interface UniformityExportPDFParams {
  data: Uniformity[];
  params: {
    location_name?: string;
    project_flock_name?: string;
    kandang_name?: string;
    start_date?: string;
    end_date?: string;
  };
}

const getParameterText = (params: UniformityExportPDFParams['params']) => {
  const paramsText = [];

  if (params.location_name && params.location_name !== 'Semua Lokasi') {
    paramsText.push(`Lokasi: ${params.location_name}`);
  }

  if (
    params.project_flock_name &&
    params.project_flock_name !== 'Semua Project Flock'
  ) {
    paramsText.push(`Project Flock: ${params.project_flock_name}`);
  }

  if (params.kandang_name && params.kandang_name !== 'Semua Kandang') {
    paramsText.push(`Kandang: ${params.kandang_name}`);
  }

  if (params.start_date && params.end_date) {
    const formattedStartDate = formatDate(params.start_date, 'DD MMM YYYY');
    const formattedEndDate = formatDate(params.end_date, 'DD MMM YYYY');
    paramsText.push(`Periode: ${formattedStartDate} - ${formattedEndDate}`);
  } else if (params.start_date) {
    const formattedStartDate = formatDate(params.start_date, 'DD MMM YYYY');
    paramsText.push(`Tanggal Mulai: ${formattedStartDate}`);
  } else if (params.end_date) {
    const formattedEndDate = formatDate(params.end_date, 'DD MMM YYYY');
    paramsText.push(`Tanggal Akhir: ${formattedEndDate}`);
  }

  const currentDate = formatDate(new Date().toISOString(), 'DD MMM YYYY HH:mm');
  paramsText.push(`Dicetak: ${currentDate}`);

  return paramsText;
};

const getStatusText = (status: string) => {
  switch (status) {
    case 'APPROVED':
      return 'Disetujui';
    case 'REJECTED':
      return 'Ditolak';
    case 'CREATED':
      return 'Pengajuan';
    default:
      return status;
  }
};

const createPDFDocument = (
  data: UniformityExportPDFParams['data'],
  params: UniformityExportPDFParams['params']
) => {
  return (
    <Document>
      <Page size='A4' orientation='landscape' style={pdfStyles.page}>
        {/* Title and Parameters */}
        <View style={pdfStyles.titleSection}>
          <Text style={pdfStyles.mainTitle}>Production &gt; Uniformity</Text>
          <View style={pdfStyles.parameterContainer}>
            {getParameterText(params).map((param, index) => (
              <View key={index} style={pdfStyles.parameterBadge}>
                <Text>{param}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Table */}
        <View style={pdfStyles.table}>
          {/* Table Header */}
          <View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
            <View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
              <Text>No</Text>
            </View>
            <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
              <Text>Lokasi</Text>
            </View>
            <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
              <Text>Project Flock</Text>
            </View>
            <View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
              <Text>Kandang</Text>
            </View>
            <View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
              <Text>Tanggal (Week)</Text>
            </View>
            <View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
              <Text>Status</Text>
            </View>
            <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
              <Text>Uniformity (%)</Text>
            </View>
            <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
              <Text>CV (%)</Text>
            </View>
            <View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
              <Text>Chick Qty</Text>
            </View>
            <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
              <Text>Uniform Qty</Text>
            </View>
            <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
              <Text>Mean Up</Text>
            </View>
            <View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
              <Text>Mean Down</Text>
            </View>
          </View>

          {/* Table Body */}
          {data.map((item: Uniformity, index: number) => (
            <View
              key={index}
              style={[
                pdfStyles.tableRow,
                index < data.length - 1 ? pdfStyles.tableBorderBottom : {},
              ]}
            >
              <View style={[pdfStyles.tableCellCenter, { flex: 0.5 }]}>
                <Text>{index + 1}</Text>
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                <Text>{item.location_name || '-'}</Text>
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                <Text>{item.flock_name || '-'}</Text>
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
                <Text>{item.kandang_name || '-'}</Text>
              </View>
              <View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
                <Text>
                  {formatDate(item.applied_at, 'DD MMM YYYY')} (Week {item.week}
                  )
                </Text>
              </View>
              <View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
                <View style={pdfStyles.badge}>
                  <Text>{getStatusText(item.status)}</Text>
                </View>
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                <Text>{formatNumber(item.uniformity)}</Text>
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                <Text>{formatNumber(item.cv)}</Text>
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
                <Text>{formatNumber(item.chick_qty_of_weight)}</Text>
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                <Text>{formatNumber(item.uniform_qty)}</Text>
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                <Text>{formatNumber(item.mean_up)}</Text>
              </View>
              <View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
                <Text>{formatNumber(item.mean_down)}</Text>
              </View>
            </View>
          ))}
        </View>
      </Page>
    </Document>
  );
};

export const generateUniformityPDF = async (
  data: UniformityExportPDFParams['data'],
  params: UniformityExportPDFParams['params']
): Promise<void> => {
  const PDFDocument = createPDFDocument(data, params);

  try {
    const blob = await pdf(PDFDocument).toBlob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;

    const period =
      params.start_date && params.end_date
        ? `${params.start_date}-${params.end_date}`
        : formatDate(new Date(), 'YYYY-MM-DD');
    link.download = `laporan-uniformity-${period}.pdf`;

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  } catch (error) {
    throw error;
  }
};
