// src/pages/admin/components/CorrectionRow.tsx
import React, { useState } from 'react';
import type { SuggestedCorrection, MasterGroceryItem, Category } from '../../../types';
import { approveCorrection, rejectCorrection, updateSuggestedCorrection } from '../../../services/apiClient'; // Ensure we are using apiClient
import { logger } from '../../../services/logger.client';
import { CheckIcon } from '../../../components/icons/CheckIcon';
import { XMarkIcon } from '../../../components/icons/XMarkIcon';
import { LoadingSpinner } from '../../../components/LoadingSpinner';
import { ConfirmationModal } from '../../../components/ConfirmationModal';
import { PencilIcon } from '../../../components/icons/PencilIcon';

interface CorrectionRowProps {
  correction: SuggestedCorrection;
  masterItems: MasterGroceryItem[];
  categories: Category[];
  onProcessed: (correctionId: number) => void;
}

export const CorrectionRow: React.FC<CorrectionRowProps> = ({ correction: initialCorrection, masterItems, categories, onProcessed }) => {
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editableValue, setEditableValue] = useState(initialCorrection.suggested_value);
  const [currentCorrection, setCurrentCorrection] = useState(initialCorrection);
  const [actionToConfirm, setActionToConfirm] = useState<'approve' | 'reject' | null>(null);

  // Helper to make the suggested value more readable for the admin.
  const formatSuggestedValue = () => {
    const { correction_type, suggested_value } = currentCorrection;
    if (correction_type === 'WRONG_PRICE') {
      const priceInCents = parseInt(suggested_value, 10);
      if (!isNaN(priceInCents)) {
        return `$${(priceInCents / 100).toFixed(2)}`;
      }
    }
    if (correction_type === 'INCORRECT_ITEM_LINK') {
      const masterItemId = parseInt(suggested_value, 10);
      const item = masterItems.find(mi => mi.master_grocery_item_id === masterItemId);
      return item ? `${item.name} (ID: ${masterItemId})` : `Unknown Item (ID: ${masterItemId})`;
    }
    if (correction_type === 'ITEM_IS_MISCATEGORIZED') {
      const categoryId = parseInt(suggested_value, 10);
      const category = categories.find(c => c.category_id === categoryId);
      return category ? `${category.name} (ID: ${categoryId})` : `Unknown Category (ID: ${categoryId})`;
    }
    return suggested_value;
  };

  const handleConfirm = async () => {
    if (!actionToConfirm) return;

    setIsProcessing(true);
    setIsModalOpen(false);
    setError(null);
    try {
      if (actionToConfirm === 'approve') {
        await approveCorrection(currentCorrection.suggested_correction_id);
        logger.info(`Correction ${currentCorrection.suggested_correction_id} approved.`);
      } else if (actionToConfirm === 'reject') {
        await rejectCorrection(currentCorrection.suggested_correction_id);
        logger.info(`Correction ${currentCorrection.suggested_correction_id} rejected.`);
      }
      onProcessed(initialCorrection.suggested_correction_id);
    } catch (err) {
      // This is a type-safe way to handle errors. We check if the caught
      // object is an instance of Error before accessing its message property.
      const errorMessage = err instanceof Error ? err.message : `An unknown error occurred while trying to ${actionToConfirm} the correction.`;
      logger.error({ err }, `Failed to ${actionToConfirm} correction ${currentCorrection.suggested_correction_id}`);
      setError(errorMessage); // Show error on the row
      setIsProcessing(false);
    }
    setActionToConfirm(null);
  };

  const handleSaveEdit = async () => {
    setIsProcessing(true);
    setError(null);
    try {
      const response = await updateSuggestedCorrection(currentCorrection.suggested_correction_id, editableValue);
      const updatedCorrection = await response.json();
      setCurrentCorrection(updatedCorrection); // Update local state with the saved version
      setIsEditing(false);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to save changes.';
      logger.error({ err }, `Failed to update correction ${currentCorrection.suggested_correction_id}`);
      setError(errorMessage);
    } finally {
      setIsProcessing(false);
    }
  };

  const renderEditableField = () => {
    switch (currentCorrection.correction_type) {
      case 'WRONG_PRICE':
        return (
          <input
            type="number"
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-input w-full text-sm dark:bg-gray-700 dark:border-gray-600"
            placeholder="Price in cents"
          />
        );
      case 'INCORRECT_ITEM_LINK':
        return (
          <select
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-select w-full text-sm dark:bg-gray-700 dark:border-gray-600"
          >
            {masterItems.map(item => <option key={item.master_grocery_item_id} value={item.master_grocery_item_id}>{item.name}</option>)}
          </select>
        );
      case 'ITEM_IS_MISCATEGORIZED':
        return (
          <select
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-select w-full text-sm dark:bg-gray-700 dark:border-gray-600"
          >
            {categories.map(cat => <option key={cat.category_id} value={cat.category_id}>{cat.name}</option>)}
          </select>
        );
      default:
        return (
          <input
            type="text"
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-input w-full text-sm dark:bg-gray-700 dark:border-gray-600"
          />);
    }
  };

  return (
    <>
      <ConfirmationModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onConfirm={handleConfirm}
        title={actionToConfirm === 'approve' ? 'Approve Correction' : 'Reject Correction'}
        message={
          actionToConfirm === 'approve' ? (
            <>
              Are you sure you want to approve this correction?
              <strong className="block mt-2">This will permanently modify the original flyer item.</strong>
            </>
          ) : (
            'Are you sure you want to reject this correction?'
          )
        }
        confirmButtonText={actionToConfirm === 'approve' ? 'Approve' : 'Reject'}
        confirmButtonClass={
          actionToConfirm === 'approve'
            ? 'bg-green-600 hover:bg-green-700 focus:ring-green-500'
            : 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
        }
      />
      <tr>
        <td className="px-6 py-4 align-top">
          <div className="text-sm font-medium text-gray-900 dark:text-white">{currentCorrection.flyer_item_name}</div>
          <div className="text-sm text-gray-500 dark:text-gray-400">Original Price: {currentCorrection.flyer_item_price_display}</div>
        </td>
        <td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400">{currentCorrection.correction_type}</td>
        <td className="px-6 py-4 align-top text-sm font-semibold text-blue-600 dark:text-blue-400">
          {isEditing ? renderEditableField() : formatSuggestedValue()}
        </td>
        <td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400">{currentCorrection.user_email || 'Unknown'}</td>
        <td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400">{new Date(currentCorrection.created_at).toLocaleDateString()}</td>
        <td className="px-6 py-4 align-top text-right text-sm font-medium">
          {isProcessing ? (
            <div className="flex justify-end items-center"><LoadingSpinner /></div>
          ) : isEditing ? (
            <div className="flex items-center justify-end space-x-2">
              <button onClick={handleSaveEdit} className="p-1.5 text-green-600 hover:bg-green-100 dark:hover:bg-green-800/50 rounded-md" title="Save"><CheckIcon className="w-5 h-5" /></button>
              <button onClick={() => { setIsEditing(false); setError(null); setEditableValue(currentCorrection.suggested_value); }} className="p-1.5 text-red-600 hover:bg-red-100 dark:hover:bg-red-800/50 rounded-md" title="Cancel"><XMarkIcon className="w-5 h-5" /></button>
            </div>
          ) : (
            <div className="flex items-center justify-end space-x-2">
              <button 
                onClick={() => {
                  setIsEditing(true);
                  setError(null);
                  setEditableValue(currentCorrection.suggested_value);
                }} 
                className="p-1.5 text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md" 
                title="Edit"
              ><PencilIcon className="w-5 h-5" /></button>
              <button onClick={() => { setActionToConfirm('approve'); setIsModalOpen(true); }} className="p-1.5 text-green-600 hover:bg-green-100 dark:hover:bg-green-800/50 rounded-md" title="Approve"><CheckIcon className="w-5 h-5" /></button>
              <button onClick={() => { setActionToConfirm('reject'); setIsModalOpen(true); }} className="p-1.5 text-red-600 hover:bg-red-100 dark:hover:bg-red-800/50 rounded-md" title="Reject"><XMarkIcon className="w-5 h-5" /></button>
            </div>
          )}
          {error && <p className="text-xs text-red-500 mt-1 text-right">{error}</p>}
        </td>
      </tr>
    </>
  );
};