/**
 * @ai-summary List of pending vehicle associations with receipt details and action buttons
 */

import React, { useState } from 'react';
import { Box } from '@mui/material';
import EmailRoundedIcon from '@mui/icons-material/EmailRounded';
import LocalGasStationRoundedIcon from '@mui/icons-material/LocalGasStationRounded';
import BuildRoundedIcon from '@mui/icons-material/BuildRounded';
import DeleteOutlineRoundedIcon from '@mui/icons-material/DeleteOutlineRounded';
import { GlassCard } from '../../../shared-minimal/components/mobile/GlassCard';
import { Button } from '../../../shared-minimal/components/Button';
import { usePendingAssociations, useDismissAssociation } from '../hooks/usePendingAssociations';
import { ResolveAssociationDialog } from './ResolveAssociationDialog';
import type { PendingVehicleAssociation } from '../types/email-ingestion.types';

export const PendingAssociationList: React.FC = () => {
  const { data: associations, isLoading, error } = usePendingAssociations();
  const dismissMutation = useDismissAssociation();
  const [resolving, setResolving] = useState<PendingVehicleAssociation | null>(null);

  if (isLoading) {
    return <PendingAssociationListSkeleton />;
  }

  if (error) {
    return (
      <GlassCard padding="md">
        <div className="text-center py-8">
          <p className="text-slate-500 dark:text-titanio">Failed to load pending receipts</p>
        </div>
      </GlassCard>
    );
  }

  if (!associations || associations.length === 0) {
    return (
      <GlassCard padding="md">
        <div className="text-center py-12">
          <Box sx={{ color: 'success.main', mb: 1.5 }}>
            <EmailRoundedIcon sx={{ fontSize: 48 }} />
          </Box>
          <h3 className="text-lg font-semibold text-slate-800 dark:text-avus mb-2">
            No Pending Receipts
          </h3>
          <p className="text-sm text-slate-500 dark:text-titanio">
            All emailed receipts have been assigned to vehicles
          </p>
        </div>
      </GlassCard>
    );
  }

  const formatDate = (dateStr: string | null): string => {
    if (!dateStr) return 'Unknown date';
    try {
      return new Date(dateStr).toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
      });
    } catch {
      return dateStr;
    }
  };

  const formatCurrency = (amount: number | null): string => {
    if (amount === null || amount === undefined) return '';
    return `$${amount.toFixed(2)}`;
  };

  return (
    <>
      <GlassCard padding="md">
        <div className="mb-4">
          <h3 className="text-lg font-semibold text-slate-800 dark:text-avus">
            Pending Receipts
          </h3>
          <p className="text-sm text-slate-500 dark:text-titanio">
            Assign a vehicle to each emailed receipt
          </p>
        </div>

        <div className="space-y-3">
          {associations.map((association) => {
            const isFuel = association.recordType === 'fuel_log';
            const IconComponent = isFuel ? LocalGasStationRoundedIcon : BuildRoundedIcon;
            const typeLabel = isFuel ? 'Fuel Receipt' : 'Maintenance Receipt';
            const { extractedData } = association;
            const merchant = extractedData.vendor || extractedData.shopName || 'Unknown merchant';

            return (
              <Box
                key={association.id}
                sx={{
                  p: 2,
                  borderRadius: 3,
                  bgcolor: 'action.hover',
                  border: '1px solid',
                  borderColor: 'divider',
                }}
              >
                <div className="flex items-start gap-3">
                  <Box
                    sx={{
                      flexShrink: 0,
                      color: isFuel ? 'info.main' : 'warning.main',
                    }}
                  >
                    <IconComponent sx={{ fontSize: 24 }} />
                  </Box>

                  <div className="flex-1 min-w-0">
                    <Box
                      component="h4"
                      sx={{ fontWeight: 600, color: 'text.primary', fontSize: '0.95rem', mb: 0.5 }}
                    >
                      {merchant}
                    </Box>

                    <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-slate-600 dark:text-titanio">
                      <span>{typeLabel}</span>
                      <span>{formatDate(extractedData.date)}</span>
                      {extractedData.total != null && (
                        <span className="font-medium">{formatCurrency(extractedData.total)}</span>
                      )}
                    </div>

                    {isFuel && extractedData.gallons != null && (
                      <p className="text-xs text-slate-400 dark:text-canna mt-1">
                        {extractedData.gallons} gal
                        {extractedData.pricePerGallon != null && ` @ $${extractedData.pricePerGallon.toFixed(3)}/gal`}
                      </p>
                    )}
                    {!isFuel && extractedData.category && (
                      <p className="text-xs text-slate-400 dark:text-canna mt-1">
                        {extractedData.category}
                        {extractedData.description && ` - ${extractedData.description}`}
                      </p>
                    )}

                    <p className="text-xs text-slate-400 dark:text-canna mt-1">
                      Received {formatDate(association.createdAt)}
                    </p>

                    <div className="flex gap-2 mt-3">
                      <Button
                        variant="primary"
                        size="sm"
                        onClick={() => setResolving(association)}
                        style={{ minHeight: 44 }}
                      >
                        Assign Vehicle
                      </Button>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => dismissMutation.mutate(association.id)}
                        disabled={dismissMutation.isPending}
                        style={{ minHeight: 44 }}
                      >
                        <DeleteOutlineRoundedIcon sx={{ fontSize: 18, mr: 0.5 }} />
                        Dismiss
                      </Button>
                    </div>
                  </div>
                </div>
              </Box>
            );
          })}
        </div>
      </GlassCard>

      {resolving && (
        <ResolveAssociationDialog
          open={!!resolving}
          association={resolving}
          onClose={() => setResolving(null)}
        />
      )}
    </>
  );
};

const PendingAssociationListSkeleton: React.FC = () => (
  <GlassCard padding="md">
    <div className="mb-4">
      <div className="h-6 bg-slate-100 dark:bg-slate-800 rounded animate-pulse w-40 mb-2" />
      <div className="h-4 bg-slate-100 dark:bg-slate-800 rounded animate-pulse w-56" />
    </div>
    <div className="space-y-3">
      {[1, 2].map((i) => (
        <div key={i} className="p-4 rounded-xl bg-slate-50 dark:bg-slate-800">
          <div className="flex items-start gap-3">
            <div className="flex-shrink-0 w-6 h-6 bg-slate-100 dark:bg-slate-700 rounded animate-pulse" />
            <div className="flex-1 space-y-2">
              <div className="h-5 bg-slate-100 dark:bg-slate-700 rounded animate-pulse w-3/4" />
              <div className="h-4 bg-slate-100 dark:bg-slate-700 rounded animate-pulse w-1/2" />
              <div className="h-4 bg-slate-100 dark:bg-slate-700 rounded animate-pulse w-1/3" />
              <div className="flex gap-2 mt-3">
                <div className="h-10 bg-slate-100 dark:bg-slate-700 rounded animate-pulse w-28" />
                <div className="h-10 bg-slate-100 dark:bg-slate-700 rounded animate-pulse w-20" />
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  </GlassCard>
);
