'use client';

import { useMemo } from 'react';
import { parseAsString, useQueryStates } from 'nuqs';
import { useSuspenseQuery } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@/components/ui/table';
import {
  crmPipelineReportQueryOptions,
  crmReportFiltersQueryOptions
} from '../api/queries';
import { ReportFilterBar } from './report-filter-bar';

function formatNumber(value: number) {
  return new Intl.NumberFormat('en-US').format(value);
}

function formatValue(value: number | null) {
  if (value === null) {
    return 'Hidden';
  }

  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  }).format(value);
}

function SectionTable({
  title,
  description,
  headers,
  rows,
  reportCode
}: {
  title: string;
  description: string;
  headers: string[];
  rows: string[][];
  reportCode?: string;
}) {
  return (
    <Card>
      <CardHeader className='flex flex-row items-start justify-between gap-4'>
        <div>
          <CardTitle>{title}</CardTitle>
          <CardDescription>{description}</CardDescription>
        </div>
        {reportCode ? <div className='text-muted-foreground text-xs'>{reportCode}</div> : null}
      </CardHeader>
      <CardContent>
        <div className='overflow-x-auto rounded-lg border'>
          <Table>
            <TableHeader>
              <TableRow>
                {headers.map((header) => (
                  <TableHead key={header}>{header}</TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.length ? (
                rows.map((row, index) => (
                  <TableRow key={`${title}-${index}`}>
                    {row.map((cell, cellIndex) => (
                      <TableCell key={`${title}-${index}-${cellIndex}`}>{cell}</TableCell>
                    ))}
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={headers.length} className='text-muted-foreground text-center'>
                    No records found.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}

export function PipelineReportView({ canExport }: { canExport: boolean }) {
  const [params] = useQueryStates({
    dateFrom: parseAsString,
    dateTo: parseAsString,
    branch: parseAsString,
    productType: parseAsString,
    sales: parseAsString,
    customerOwner: parseAsString,
    leadSource: parseAsString
  });
  const filters = useMemo(
    () => ({
      dateFrom: params.dateFrom,
      dateTo: params.dateTo,
      branch: params.branch,
      productType: params.productType,
      sales: params.sales,
      customerOwner: params.customerOwner,
      leadSource: params.leadSource
    }),
    [params]
  );
  const { data: filterData } = useSuspenseQuery(crmReportFiltersQueryOptions());
  const { data } = useSuspenseQuery(crmPipelineReportQueryOptions(filters));

  return (
    <div className='space-y-6'>
      <ReportFilterBar
        filterMetadata={filterData.filters}
        filterKeys={['dateFrom', 'dateTo', 'branch', 'productType', 'sales', 'customerOwner', 'leadSource']}
        canExport={canExport}
        reportCode='pipeline_funnel'
        pageLinks={[
          { href: '/dashboard/crm/reports/pipeline', label: 'Pipeline Suite', active: true },
          { href: '/dashboard/crm/reports/lead-aging', label: 'Lead Aging' },
          { href: '/dashboard/crm/reports/opportunity-aging', label: 'Opportunity Aging' }
        ]}
      />

      <div className='grid gap-4 md:grid-cols-2 xl:grid-cols-5'>
        {[
          ['Total Leads', formatNumber(data.summary.totalLeads)],
          ['Open Opportunities', formatNumber(data.summary.openOpportunities)],
          ['Quotations', formatNumber(data.summary.quotations)],
          ['Closed Won', formatNumber(data.summary.won)],
          ['Closed Lost', formatNumber(data.summary.lost)]
        ].map(([label, value]) => (
          <Card key={String(label)}>
            <CardHeader className='pb-2'>
              <CardDescription>{label}</CardDescription>
            </CardHeader>
            <CardContent>
              <div className='text-2xl font-semibold'>{value}</div>
            </CardContent>
          </Card>
        ))}
      </div>

      <SectionTable
        title='Pipeline Funnel'
        description={
          data.summary.canViewRevenueValues
            ? 'Lead to won/lost funnel with count, value, and conversion rate.'
            : 'Lead to won/lost funnel with count and conversion rate. Revenue values are hidden by access policy.'
        }
        reportCode='pipeline_funnel'
        headers={['Stage', 'Count', 'Value', 'Conversion %']}
        rows={data.funnel.map((row) => [
          row.stageLabel,
          formatNumber(row.count),
          formatValue(row.value),
          row.conversionRate === null ? '-' : `${row.conversionRate}%`
        ])}
      />

      <SectionTable
        title='Lead Pipeline'
        description='Marketing view grouped by source, owner, creator, branch, and product type.'
        reportCode='lead_pipeline'
        headers={[
          'Lead Source',
          'Customer Owner',
          'Created By',
          'Branch',
          'Product Type',
          'Total',
          'Assigned',
          'Unassigned',
          'Converted'
        ]}
        rows={data.leadPipeline.map((row) => [
          row.leadSourceLabel,
          row.customerOwnerName,
          row.createdByName,
          row.branchLabel,
          row.productTypeLabel,
          formatNumber(row.totalLeads),
          formatNumber(row.assignedLeads),
          formatNumber(row.unassignedLeads),
          formatNumber(row.convertedLeads)
        ])}
      />

      <SectionTable
        title='Opportunity Pipeline'
        description='Sales pipeline visibility grouped by salesman, branch, product type, and customer owner.'
        reportCode='opportunity_pipeline'
        headers={[
          'Salesman',
          'Branch',
          'Product Type',
          'Customer Owner',
          'Open',
          'With Quotation',
          'Won',
          'Lost'
        ]}
        rows={data.opportunityPipeline.map((row) => [
          row.salesmanName,
          row.branchLabel,
          row.productTypeLabel,
          row.customerOwnerName,
          formatNumber(row.openOpportunities),
          formatNumber(row.convertedToQuotation),
          formatNumber(row.won),
          formatNumber(row.lost)
        ])}
      />

      <div className='grid gap-6 xl:grid-cols-2'>
        <SectionTable
          title='Lead to Opportunity Conversion'
          description='Marketing effectiveness by source, branch, product type, and creator.'
          reportCode='lead_conversion'
          headers={['Lead Source', 'Branch', 'Product Type', 'Marketing User', 'Total Leads', 'Converted', 'Conversion %']}
          rows={data.leadConversion.map((row) => [
            row.leadSourceLabel,
            row.branchLabel,
            row.productTypeLabel,
            row.marketingUserName,
            formatNumber(row.totalLeads),
            formatNumber(row.convertedOpportunities),
            `${row.conversionRate}%`
          ])}
        />

        <SectionTable
          title='Opportunity to Quotation Conversion'
          description='Sales effectiveness by salesman, branch, and product type.'
          reportCode='opportunity_conversion'
          headers={['Salesman', 'Branch', 'Product Type', 'Total Opportunities', 'With Quotation', 'Conversion %']}
          rows={data.opportunityConversion.map((row) => [
            row.salesmanName,
            row.branchLabel,
            row.productTypeLabel,
            formatNumber(row.totalOpportunities),
            formatNumber(row.opportunitiesWithQuotation),
            `${row.conversionRate}%`
          ])}
        />
      </div>
    </div>
  );
}

