/**
 * @ai-summary List component for displaying ownership costs
 */

import React from 'react';
import type { OwnershipCost, OwnershipCostType } from '../types/ownership-costs.types';
import { useOwnershipCostsList, useDeleteOwnershipCost } from '../hooks/useOwnershipCosts';

interface OwnershipCostsListProps {
  vehicleId?: string;
  onEdit?: (cost: OwnershipCost) => void;
}

const COST_TYPE_LABELS: Record<OwnershipCostType, string> = {
  insurance: 'Insurance',
  registration: 'Registration',
  tax: 'Tax',
  inspection: 'Inspection',
  parking: 'Parking',
  other: 'Other',
};

export const OwnershipCostsList: React.FC<OwnershipCostsListProps> = ({ vehicleId, onEdit }) => {
  const { data: costs, isLoading, error } = useOwnershipCostsList(vehicleId ? { vehicleId } : undefined);
  const deleteMutation = useDeleteOwnershipCost();
  const [deleteConfirm, setDeleteConfirm] = React.useState<string | null>(null);

  const handleDelete = async (id: string) => {
    try {
      await deleteMutation.mutateAsync(id);
      setDeleteConfirm(null);
    } catch (err) {
      console.error('Failed to delete cost:', err);
    }
  };

  const formatCurrency = (value: number): string => {
    return value.toLocaleString(undefined, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });
  };

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleDateString();
  };

  if (isLoading) {
    return (
      <div className="animate-pulse space-y-4">
        {[1, 2].map((i) => (
          <div key={i} className="h-24 bg-gray-200 dark:bg-silverstone rounded-lg" />
        ))}
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-sm text-gray-500 dark:text-titanio p-4 bg-gray-50 dark:bg-scuro rounded-lg border border-gray-200 dark:border-silverstone">
        <p>Unable to load ownership costs.</p>
      </div>
    );
  }

  if (!costs || costs.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500 dark:text-titanio">
        <p>No ownership costs recorded yet.</p>
        <p className="text-sm mt-1">Track insurance, registration, taxes, and other recurring vehicle costs.</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {costs.map((cost) => (
        <div
          key={cost.id}
          className="p-4 bg-white dark:bg-jet rounded-lg border border-gray-200 dark:border-silverstone"
        >
          <div className="flex justify-between items-start">
            <div className="flex-1">
              <div className="flex items-center gap-2">
                <span className="font-medium text-gray-900 dark:text-avus">
                  {COST_TYPE_LABELS[cost.costType]}
                </span>
              </div>
              {cost.description && (
                <p className="text-sm text-gray-500 dark:text-titanio mt-1">
                  {cost.description}
                </p>
              )}
              {(cost.periodStart || cost.periodEnd) && (
                <p className="text-xs text-gray-400 dark:text-canna mt-2">
                  {cost.periodStart && formatDate(cost.periodStart)}
                  {cost.periodStart && cost.periodEnd && ' - '}
                  {cost.periodEnd && formatDate(cost.periodEnd)}
                </p>
              )}
              {cost.notes && (
                <p className="text-xs text-gray-500 dark:text-titanio mt-2">
                  {cost.notes}
                </p>
              )}
            </div>
            <div className="text-right ml-4">
              <div className="text-lg font-semibold text-gray-900 dark:text-avus">
                ${formatCurrency(cost.amount)}
              </div>
              <div className="flex gap-2 mt-2">
                {onEdit && (
                  <button
                    onClick={() => onEdit(cost)}
                    className="text-sm text-primary-600 dark:text-abudhabi hover:underline min-h-[44px] px-2"
                  >
                    Edit
                  </button>
                )}
                {deleteConfirm === cost.id ? (
                  <div className="flex gap-1">
                    <button
                      onClick={() => handleDelete(cost.id)}
                      className="text-sm text-red-600 hover:underline min-h-[44px] px-2"
                    >
                      Confirm
                    </button>
                    <button
                      onClick={() => setDeleteConfirm(null)}
                      className="text-sm text-gray-500 hover:underline min-h-[44px] px-2"
                    >
                      Cancel
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={() => setDeleteConfirm(cost.id)}
                    className="text-sm text-red-600 hover:underline min-h-[44px] px-2"
                  >
                    Delete
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};
