import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { useNumerology } from '../../hooks/useNumerology';
import { SavedCalculation } from '../../services/api';
import { format } from 'date-fns';
import { 
  Calculator, 
  Calendar, 
  User, 
  Briefcase, 
  Trash2, 
  Eye, 
  Plus,
  AlertCircle,
  Loader
} from 'lucide-react';

const MyCalculations: React.FC = () => {
  const { 
    userCalculations, 
    deleteCalculation, 
    isLoadingUserCalculations, 
    isDeleting, 
    userCalculationsError 
  } = useNumerology();
  
  const [selectedCalculation, setSelectedCalculation] = useState<SavedCalculation | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const handleDelete = async (id: number) => {
    if (window.confirm('Are you sure you want to delete this calculation?')) {
      setDeletingId(id);
      const result = await deleteCalculation(id);
      setDeletingId(null);
      
      if (!result.success) {
        alert('Failed to delete calculation: ' + result.error);
      }
    }
  };

  const handleView = (calculation: SavedCalculation) => {
    setSelectedCalculation(calculation);
  };

  if (isLoadingUserCalculations) {
    return (
      <div className="min-h-96 flex items-center justify-center">
        <div className="flex items-center space-x-2 text-purple-600">
          <Loader className="h-6 w-6 animate-spin" />
          <span>Loading your calculations...</span>
        </div>
      </div>
    );
  }

  if (userCalculationsError) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-xl p-6 text-center">
        <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
        <h3 className="text-lg font-semibold text-red-800 mb-2">Error Loading Calculations</h3>
        <p className="text-red-600">{userCalculationsError}</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="text-center text-white space-y-4">
        <div className="flex items-center justify-center space-x-3">
          <Calculator className="h-12 w-12" />
          <h1 className="text-4xl md:text-5xl font-bold">My Calculations</h1>
        </div>
        <p className="text-xl opacity-90 max-w-2xl mx-auto">
          View and manage your saved numerology analyses
        </p>
      </div>

      {/* Add New Calculation Button */}
      <div className="text-center">
        <Link
          to="/calculator"
          className="inline-flex items-center space-x-2 px-6 py-3 bg-white text-purple-600 font-semibold rounded-xl hover:bg-gray-100 transition-all duration-300 transform hover:scale-105 shadow-lg"
        >
          <Plus className="h-5 w-5" />
          <span>New Calculation</span>
        </Link>
      </div>

      {/* Calculations Grid */}
      {userCalculations.length === 0 ? (
        <div className="bg-white rounded-xl shadow-lg p-12 text-center">
          <Calculator className="h-16 w-16 text-gray-300 mx-auto mb-6" />
          <h3 className="text-xl font-semibold text-gray-600 mb-3">No Calculations Yet</h3>
          <p className="text-gray-500 mb-6">
            You haven't saved any numerology calculations yet. Create your first analysis to get started!
          </p>
          <Link
            to="/calculator"
            className="inline-flex items-center space-x-2 px-6 py-3 bg-purple-600 text-white font-medium rounded-lg hover:bg-purple-700 transition-colors duration-300"
          >
            <Plus className="h-5 w-5" />
            <span>Create First Calculation</span>
          </Link>
        </div>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {userCalculations.map((calculation) => (
            <div
              key={calculation.id}
              className="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1"
            >
              {/* Header */}
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center space-x-2">
                  <div className="w-10 h-10 bg-purple-600 text-white rounded-full flex items-center justify-center text-lg font-bold">
                    {calculation.root_number}
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-800">{calculation.name}</h3>
                    <p className="text-sm text-gray-500">Root #{calculation.root_number}</p>
                  </div>
                </div>
                <div className="flex space-x-2">
                  <button
                    onClick={() => handleView(calculation)}
                    className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors duration-200"
                    title="View Details"
                  >
                    <Eye className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(calculation.id)}
                    disabled={deletingId === calculation.id}
                    className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors duration-200 disabled:opacity-50"
                    title="Delete"
                  >
                    {deletingId === calculation.id ? (
                      <Loader className="h-4 w-4 animate-spin" />
                    ) : (
                      <Trash2 className="h-4 w-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* Details */}
              <div className="space-y-2 text-sm">
                <div className="flex items-center space-x-2 text-gray-600">
                  <Calendar className="h-4 w-4" />
                  <span>{format(new Date(calculation.birthdate), 'MMM dd, yyyy')}</span>
                </div>
                {calculation.industry && (
                  <div className="flex items-center space-x-2 text-gray-600">
                    <Briefcase className="h-4 w-4" />
                    <span>{calculation.industry}</span>
                  </div>
                )}
                <div className="flex items-center space-x-2 text-gray-600">
                  <User className="h-4 w-4" />
                  <span>Created {format(new Date(calculation.created_at), 'MMM dd, yyyy')}</span>
                </div>
              </div>

              {/* SWOT Summary */}
              {calculation.swot_combinations && calculation.swot_combinations.length > 0 && (
                <div className="mt-4 pt-4 border-t border-gray-100">
                  <div className="text-sm text-gray-600">
                    <span className="font-medium">SWOT Patterns:</span>
                    <span className="ml-2">{calculation.swot_combinations.length} found</span>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Detailed View Modal */}
      {selectedCalculation && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-96 overflow-y-auto">
            <div className="p-6">
              {/* Modal Header */}
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-2xl font-bold text-gray-800">
                  {selectedCalculation.name} - Calculation Details
                </h3>
                <button
                  onClick={() => setSelectedCalculation(null)}
                  className="text-gray-400 hover:text-gray-600 transition-colors duration-200"
                >
                  <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              {/* Calculation Details */}
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <span className="text-sm font-medium text-gray-700">Birthdate:</span>
                    <p className="text-gray-900">{format(new Date(selectedCalculation.birthdate), 'MMMM dd, yyyy')}</p>
                  </div>
                  <div>
                    <span className="text-sm font-medium text-gray-700">Root Number:</span>
                    <p className="text-gray-900 text-lg font-bold">{selectedCalculation.root_number}</p>
                  </div>
                  {selectedCalculation.industry && (
                    <div>
                      <span className="text-sm font-medium text-gray-700">Industry:</span>
                      <p className="text-gray-900">{selectedCalculation.industry}</p>
                    </div>
                  )}
                  <div>
                    <span className="text-sm font-medium text-gray-700">Created:</span>
                    <p className="text-gray-900">{format(new Date(selectedCalculation.created_at), 'MMM dd, yyyy HH:mm')}</p>
                  </div>
                </div>

                {/* Pyramid Values */}
                <div>
                  <span className="text-sm font-medium text-gray-700">Pyramid Values:</span>
                  <div className="mt-2 grid grid-cols-5 gap-2 text-sm">
                    <div>
                      <div className="font-medium">L5:</div>
                      <div className="text-gray-600">[{selectedCalculation.L5.join(', ')}]</div>
                    </div>
                    <div>
                      <div className="font-medium">L6:</div>
                      <div className="text-gray-600">[{selectedCalculation.L6.join(', ')}]</div>
                    </div>
                    <div>
                      <div className="font-medium">L7:</div>
                      <div className="text-gray-600">[{selectedCalculation.L7.join(', ')}]</div>
                    </div>
                    <div>
                      <div className="font-medium">L8:</div>
                      <div className="text-gray-600">[{selectedCalculation.L8.join(', ')}]</div>
                    </div>
                    <div>
                      <div className="font-medium">L9:</div>
                      <div className="text-gray-600">[{selectedCalculation.L9.join(', ')}]</div>
                    </div>
                  </div>
                </div>

                {/* SWOT Combinations */}
                {selectedCalculation.swot_combinations && selectedCalculation.swot_combinations.length > 0 && (
                  <div>
                    <span className="text-sm font-medium text-gray-700">SWOT Patterns:</span>
                    <div className="mt-2 space-y-2">
                      {selectedCalculation.swot_combinations.map((combo, index) => (
                        <div key={index} className="flex items-center space-x-3 p-2 bg-gray-50 rounded-lg">
                          <span className="font-mono font-bold">{combo.sequence}</span>
                          <span className={`px-2 py-1 rounded text-xs font-bold ${
                            combo.label === 'S' ? 'bg-green-100 text-green-800' :
                            combo.label === 'W' ? 'bg-red-100 text-red-800' :
                            combo.label === 'O' ? 'bg-blue-100 text-blue-800' :
                            'bg-yellow-100 text-yellow-800'
                          }`}>
                            {combo.label}
                          </span>
                          <span className="text-sm text-gray-600 flex-1">{combo.description}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MyCalculations;