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

import React, { useState } from 'react';
import {
  OwnershipCost,
  CreateOwnershipCostRequest,
  COST_TYPE_LABELS,
  INTERVAL_LABELS
} from '../types/ownership-costs.types';
import { OwnershipCostForm } from './OwnershipCostForm';
import { useOwnershipCosts } from '../hooks/useOwnershipCosts';
import { Button } from '../../../shared-minimal/components/Button';

interface OwnershipCostsListProps {
  vehicleId: string;
}

export const OwnershipCostsList: React.FC<OwnershipCostsListProps> = ({
  vehicleId,
}) => {
  const { costs, isLoading, error, createCost, updateCost, deleteCost } = useOwnershipCosts(vehicleId);
  const [showForm, setShowForm] = useState(false);
  const [editingCost, setEditingCost] = useState<OwnershipCost | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  const handleSubmit = async (data: Omit<CreateOwnershipCostRequest, 'vehicleId'>) => {
    setIsSubmitting(true);
    try {
      if (editingCost) {
        await updateCost(editingCost.id, data);
      } else {
        await createCost({ ...data, vehicleId });
      }
      setShowForm(false);
      setEditingCost(null);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEdit = (cost: OwnershipCost) => {
    setEditingCost(cost);
    setShowForm(true);
  };

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

  const handleCancel = () => {
    setShowForm(false);
    setEditingCost(null);
  };

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

  // Format date
  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) {
    // Show a subtle message if the feature isn't set up yet, don't block the page
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-medium text-gray-900 dark:text-avus">
            Recurring Costs
          </h3>
        </div>
        <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>Recurring costs tracking is being set up.</p>
          <p className="text-xs mt-1 text-gray-400 dark:text-canna">Run migrations to enable this feature.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-medium text-gray-900 dark:text-avus">
          Recurring Costs
        </h3>
        {!showForm && (
          <Button
            variant="secondary"
            onClick={() => setShowForm(true)}
            className="text-sm"
          >
            Add Cost
          </Button>
        )}
      </div>

      {showForm && (
        <div className="p-4 bg-gray-50 dark:bg-scuro rounded-lg border border-gray-200 dark:border-silverstone">
          <h4 className="text-md font-medium text-gray-900 dark:text-avus mb-4">
            {editingCost ? 'Edit Cost' : 'Add New Cost'}
          </h4>
          <OwnershipCostForm
            vehicleId={vehicleId}
            initialData={editingCost || undefined}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            loading={isSubmitting}
          />
        </div>
      )}

      {costs.length === 0 && !showForm ? (
        <div className="text-center py-8 text-gray-500 dark:text-titanio">
          <p>No recurring costs added yet.</p>
          <p className="text-sm mt-1">Track insurance, registration, and other recurring vehicle costs.</p>
        </div>
      ) : (
        <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>
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-gray-900 dark:text-avus">
                      {COST_TYPE_LABELS[cost.costType]}
                    </span>
                    <span className="text-xs px-2 py-0.5 bg-gray-100 dark:bg-silverstone text-gray-600 dark:text-titanio rounded">
                      {INTERVAL_LABELS[cost.interval]}
                    </span>
                  </div>
                  {cost.description && (
                    <p className="text-sm text-gray-500 dark:text-titanio mt-1">
                      {cost.description}
                    </p>
                  )}
                  <p className="text-xs text-gray-400 dark:text-canna mt-2">
                    {formatDate(cost.startDate)}
                    {cost.endDate ? ` - ${formatDate(cost.endDate)}` : ' - Ongoing'}
                  </p>
                </div>
                <div className="text-right">
                  <div className="text-lg font-semibold text-gray-900 dark:text-avus">
                    ${formatCurrency(cost.amount)}
                  </div>
                  <div className="flex gap-2 mt-2">
                    <button
                      onClick={() => handleEdit(cost)}
                      className="text-sm text-primary-600 dark:text-abudhabi hover:underline"
                    >
                      Edit
                    </button>
                    {deleteConfirm === cost.id ? (
                      <div className="flex gap-1">
                        <button
                          onClick={() => handleDelete(cost.id)}
                          className="text-sm text-red-600 hover:underline"
                        >
                          Confirm
                        </button>
                        <button
                          onClick={() => setDeleteConfirm(null)}
                          className="text-sm text-gray-500 hover:underline"
                        >
                          Cancel
                        </button>
                      </div>
                    ) : (
                      <button
                        onClick={() => setDeleteConfirm(cost.id)}
                        className="text-sm text-red-600 hover:underline"
                      >
                        Delete
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
