import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { usePMScheduleDetails, usePMScheduleMutations } from '../hooks/usePMSchedule';
import { useAssetMaintenanceLogs } from '../hooks/useAssetMaintenance';
import { FaArrowLeft, FaSave, FaEdit, FaCalendarAlt, FaTrash, FaSpinner, FaCheckCircle } from 'react-icons/fa';
import LinkField from '../components/LinkField';

const PPMPlannerDetail: React.FC = () => {
  const { scheduleName } = useParams<{ scheduleName: string }>();
  const navigate = useNavigate();
  
  const { pmSchedule, loading, error, refetch } = usePMScheduleDetails(scheduleName || null);
  const { updatePMSchedule, deletePMSchedule, submitPMSchedule, cancelPMSchedule, loading: saving } = usePMScheduleMutations();
  
  // Fetch all maintenance logs to link with assets
  const { logs: maintenanceLogs } = useAssetMaintenanceLogs({}, 10000, 0);
  
  const [isEditing, setIsEditing] = useState(false);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [formData, setFormData] = useState({
    hospital: '',
    modality: '',
    device_status: '',
    start_date: '',
    end_date: '',
    maintenance_team: '',
    maintenance_manager: '',
    periodicity: 'Monthly',
    assign_to: '',
    due_date: '',
    next_pm_date: '',
    manufacturer: '',
    model: '',
    pm_for: '',
    asset_name: '',
    no_of_pms: ''
  });

  // Helper function to calculate next PM date for an asset
  const calculateNextPMDateForAsset = (assetName: string, periodicity: string, defaultDueDate: string): string | null => {
    if (!periodicity || !defaultDueDate) {
      return null;
    }

    // Find maintenance logs for this asset
    const assetLogs = maintenanceLogs.filter(log => log.asset_name === assetName);
    
    // Find the most recent completed maintenance log
    const completedLogs = assetLogs
      .filter(log => log.maintenance_status === 'Completed' && log.completion_date)
      .sort((a, b) => {
        const dateA = new Date(a.completion_date || 0).getTime();
        const dateB = new Date(b.completion_date || 0).getTime();
        return dateB - dateA; // Most recent first
      });

    if (completedLogs.length === 0) {
      // No completed logs, use the original due_date (First PM Date)
      return defaultDueDate;
    }

    const lastCompletedLog = completedLogs[0];
    const lastDueDate = new Date(lastCompletedLog.due_date || defaultDueDate);
    const lastCompletionDate = new Date(lastCompletedLog.completion_date!);
    
    // Calculate delay (days)
    const delayDays = Math.max(0, Math.floor((lastCompletionDate.getTime() - lastDueDate.getTime()) / (1000 * 60 * 60 * 24)));
    
    // Calculate next due date based on periodicity
    const nextDueDate = new Date(lastCompletionDate);
    
    switch (periodicity) {
      case 'Daily':
        nextDueDate.setDate(nextDueDate.getDate() + 1);
        break;
      case 'Weekly':
        nextDueDate.setDate(nextDueDate.getDate() + 7);
        break;
      case 'Monthly':
        nextDueDate.setMonth(nextDueDate.getMonth() + 1);
        break;
      case 'Quarterly':
        nextDueDate.setMonth(nextDueDate.getMonth() + 3);
        break;
      case 'Half-yearly':
        nextDueDate.setMonth(nextDueDate.getMonth() + 6);
        break;
      case 'Yearly':
        nextDueDate.setFullYear(nextDueDate.getFullYear() + 1);
        break;
      case '2 Yearly':
        nextDueDate.setFullYear(nextDueDate.getFullYear() + 2);
        break;
      case '3 Yearly':
        nextDueDate.setFullYear(nextDueDate.getFullYear() + 3);
        break;
      default:
        return defaultDueDate;
    }
    
    // Add the delay to the next due date
    nextDueDate.setDate(nextDueDate.getDate() + delayDays);
    
    // Format as YYYY-MM-DD
    const year = nextDueDate.getFullYear();
    const month = String(nextDueDate.getMonth() + 1).padStart(2, '0');
    const day = String(nextDueDate.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // Calculate overall next PM date (earliest among all assets) and update formData
  useEffect(() => {
    if (pmSchedule && pmSchedule.maintenance_entries && maintenanceLogs.length > 0) {
      const nextDates: string[] = [];
      
      pmSchedule.maintenance_entries.forEach((entry: any) => {
        const nextDate = calculateNextPMDateForAsset(
          entry.asset,
          pmSchedule.periodicity || 'Monthly',
          pmSchedule.due_date || ''
        );
        if (nextDate) {
          nextDates.push(nextDate);
        }
      });
      
      if (nextDates.length > 0) {
        // Find the earliest next PM date
        const earliestDate = nextDates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime())[0];
        
        // Update formData if it's different
        setFormData(prev => {
          if (prev.next_pm_date !== earliestDate) {
            return {
              ...prev,
              next_pm_date: earliestDate
            };
          }
          return prev;
        });
      }
    }
  }, [pmSchedule, maintenanceLogs]);

  useEffect(() => {
    if (pmSchedule) {
      setFormData({
        hospital: pmSchedule.hospital || '',
        modality: pmSchedule.modality || '',
        device_status: pmSchedule.device_status || '',
        start_date: pmSchedule.start_date || '',
        end_date: pmSchedule.end_date || '',
        maintenance_team: pmSchedule.maintenance_team || '',
        maintenance_manager: pmSchedule.maintenance_manager || '',
        periodicity: pmSchedule.periodicity || 'Monthly',
        assign_to: pmSchedule.assign_to || '',
        due_date: pmSchedule.due_date || '',
        next_pm_date: pmSchedule.next_pm_date || '',
        manufacturer: pmSchedule.manufacturer || '',
        model: pmSchedule.model || '',
        pm_for: pmSchedule.pm_for || '',
        asset_name: pmSchedule.asset_name || '',
        no_of_pms: pmSchedule.no_of_pms || ''
      });
    }
  }, [pmSchedule]);

  // Helper function to calculate end_date based on start_date, periodicity, and no_of_pms
  const calculateEndDate = (startDate: string, periodicity: string, noOfPms: string): string | null => {
    if (!startDate || !periodicity || !noOfPms) {
      return null;
    }

    const noOfPmsNum = parseInt(noOfPms, 10);
    if (isNaN(noOfPmsNum) || noOfPmsNum < 1) {
      return null;
    }

    // Start date is PM #1, so we need to add (no_of_pms - 1) periods
    const occurrences = noOfPmsNum - 1;
    if (occurrences < 0) {
      return null;
    }

    const start = new Date(startDate);
    const end = new Date(start);

    switch (periodicity) {
      case 'Daily':
        end.setDate(end.getDate() + occurrences);
        break;
      case 'Weekly':
        end.setDate(end.getDate() + (occurrences * 7));
        break;
      case 'Monthly':
        end.setMonth(end.getMonth() + occurrences);
        break;
      case 'Quarterly':
        end.setMonth(end.getMonth() + (occurrences * 3));
        break;
      case 'Half-yearly':
        end.setMonth(end.getMonth() + (occurrences * 6));
        break;
      case 'Yearly':
        end.setFullYear(end.getFullYear() + occurrences);
        break;
      case '2 Yearly':
        end.setFullYear(end.getFullYear() + (occurrences * 2));
        break;
      case '3 Yearly':
        end.setFullYear(end.getFullYear() + (occurrences * 3));
        break;
      default:
        return null;
    }

    // Format as YYYY-MM-DD
    const year = end.getFullYear();
    const month = String(end.getMonth() + 1).padStart(2, '0');
    const day = String(end.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    setFormData(prev => {
      const updated = {
        ...prev,
        [name]: value
      };

      // Auto-calculate end_date when start_date, periodicity, or no_of_pms changes
      if (name === 'start_date' || name === 'periodicity' || name === 'no_of_pms') {
        const calculatedEndDate = calculateEndDate(
          name === 'start_date' ? value : prev.start_date,
          name === 'periodicity' ? value : prev.periodicity,
          name === 'no_of_pms' ? value : prev.no_of_pms
        );
        
        if (calculatedEndDate) {
          updated.end_date = calculatedEndDate;
        }
      }

      return updated;
    });
  };

  const handleSave = async () => {
    if (!scheduleName) return;
    
    try {
      await updatePMSchedule(scheduleName, formData);
      setIsEditing(false);
      refetch();
      alert('PPM Planner updated successfully');
    } catch (err) {
      console.error('Error updating PPM Planner:', err);
      alert('Failed to update PPM Planner');
    }
  };

  const handleDelete = async () => {
    if (!scheduleName) return;
    
    try {
      await deletePMSchedule(scheduleName);
      navigate('/ppm-planner');
    } catch (err) {
      console.error('Error deleting PPM Planner:', err);
      alert('Failed to delete PPM Planner');
    }
  };

  const handleSubmit = async () => {
    if (!scheduleName) return;
    
    try {
      await submitPMSchedule(scheduleName);
      refetch();
      alert('PPM Planner submitted successfully');
    } catch (err) {
      console.error('Error submitting PPM Planner:', err);
      alert('Failed to submit PPM Planner');
    }
  };

  const handleCancel = async () => {
    if (!scheduleName) return;
    
    try {
      await cancelPMSchedule(scheduleName);
      refetch();
      alert('PPM Planner cancelled successfully');
    } catch (err) {
      console.error('Error cancelling PPM Planner:', err);
      alert('Failed to cancel PPM Planner');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="flex items-center gap-3">
          <FaSpinner className="animate-spin text-blue-600" size={24} />
          <span className="text-gray-600 dark:text-gray-400">Loading PPM Planner...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-600 dark:text-red-400">{error}</p>
          <button
            onClick={() => navigate('/ppm-planner')}
            className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            Back to List
          </button>
        </div>
      </div>
    );
  }

  if (!pmSchedule) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
          <p className="text-yellow-600 dark:text-yellow-400">PPM Planner not found</p>
          <button
            onClick={() => navigate('/ppm-planner')}
            className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            Back to List
          </button>
        </div>
      </div>
    );
  }

  const isDraft = pmSchedule.docstatus === 0;
  const isSubmitted = pmSchedule.docstatus === 1;
  const isCancelled = pmSchedule.docstatus === 2;

  return (
    <div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <div className="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4">
        <div className="flex justify-between items-center mb-4">
          <div className="flex items-center gap-3">
            <button
              onClick={() => navigate('/ppm-planner')}
              className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              <FaArrowLeft className="text-gray-600 dark:text-gray-400" />
            </button>
            <FaCalendarAlt className="text-blue-600 dark:text-blue-400" size={28} />
            <div>
              <h1 className="text-2xl font-bold text-gray-800 dark:text-white">{pmSchedule.name}</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                PPM Planner Details
              </p>
            </div>
            <span className={`ml-4 px-3 py-1 text-sm font-semibold rounded-full ${
              isSubmitted
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : isDraft
                ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400'
                : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400'
            }`}>
              {isSubmitted ? 'Submitted' : isDraft ? 'Draft' : 'Cancelled'}
            </span>
          </div>
          <div className="flex gap-2">
            {isDraft && !isEditing && (
              <>
                <button
                  onClick={() => setIsEditing(true)}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2"
                >
                  <FaEdit />
                  Edit
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={saving}
                  className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  <FaCheckCircle />
                  Submit
                </button>
                <button
                  onClick={() => setDeleteConfirmOpen(true)}
                  disabled={saving}
                  className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  <FaTrash />
                  Delete
                </button>
              </>
            )}
            {isEditing && (
              <>
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  Save
                </button>
                <button
                  onClick={() => {
                    setIsEditing(false);
                    setFormData({
                      hospital: pmSchedule.hospital || '',
                      modality: pmSchedule.modality || '',
                      device_status: pmSchedule.device_status || '',
                      start_date: pmSchedule.start_date || '',
                      end_date: pmSchedule.end_date || '',
                      maintenance_team: pmSchedule.maintenance_team || '',
                      maintenance_manager: pmSchedule.maintenance_manager || '',
                      periodicity: pmSchedule.periodicity || 'Monthly',
                      assign_to: pmSchedule.assign_to || '',
                      due_date: pmSchedule.due_date || '',
                      next_pm_date: pmSchedule.next_pm_date || '',
                      manufacturer: pmSchedule.manufacturer || '',
                      model: pmSchedule.model || '',
                      pm_for: pmSchedule.pm_for || '',
                      asset_name: pmSchedule.asset_name || '',
                      no_of_pms: pmSchedule.no_of_pms || ''
                    });
                  }}
                  disabled={saving}
                  className="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors disabled:opacity-50"
                >
                  Cancel
                </button>
              </>
            )}
            {isSubmitted && (
              <button
                onClick={handleCancel}
                disabled={saving}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
              >
                Cancel Document
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-auto p-6">
        <div className="max-w-4xl mx-auto bg-white dark:bg-gray-800 rounded-lg shadow">
          <div className="p-6 space-y-6">
            {/* Basic Information */}
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Basic Information</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  {/* <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Hospital *
                  </label> */}
                  {isEditing ? (
                    <LinkField
                      label = "Hospital *"
                      doctype="Company"
                      value={formData.hospital}
                      onChange={(value) => setFormData(prev => ({ ...prev, hospital: value }))}
                      placeholder="Select Hospital"
                      filters={{}}
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.hospital || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Modality
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="modality"
                      value={formData.modality}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.modality || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Device Status
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="device_status"
                      value={formData.device_status}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.device_status || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Periodicity *
                  </label>
                  {isEditing ? (
                    <select
                      name="periodicity"
                      value={formData.periodicity}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    >
                      <option value="Daily">Daily</option>
                      <option value="Weekly">Weekly</option>
                      <option value="Monthly">Monthly</option>
                      <option value="Quarterly">Quarterly</option>
                      <option value="Half-yearly">Half-yearly</option>
                      <option value="Yearly">Yearly</option>
                    </select>
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.periodicity || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Manufacturer
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="manufacturer"
                      value={formData.manufacturer}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.manufacturer || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Model
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="model"
                      value={formData.model}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.model || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    PM Name
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="pm_for"
                      value={formData.pm_for}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.pm_for || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Asset Name
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="asset_name"
                      value={formData.asset_name}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.asset_name || '-'}
                    </div>
                  )}
                </div>

              </div>
            </div>

            {/* Schedule Dates */}
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Schedule Dates</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Start Date *
                  </label>
                  {isEditing ? (
                    <input
                      type="date"
                      name="start_date"
                      value={formData.start_date}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.start_date ? new Date(pmSchedule.start_date).toLocaleDateString() : '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    End Date *
                  </label>
                  {isEditing ? (
                    <input
                      type="date"
                      name="end_date"
                      value={formData.end_date}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.end_date ? new Date(pmSchedule.end_date).toLocaleDateString() : '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    First PM Date
                  </label>
                  {isEditing ? (
                    <input
                      type="date"
                      name="due_date"
                      value={formData.due_date}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.due_date ? new Date(pmSchedule.due_date).toLocaleDateString() : '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Next PM Date
                  </label>
                  {isEditing ? (
                    <input
                      type="date"
                      name="next_pm_date"
                      value={formData.next_pm_date}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {formData.next_pm_date ? new Date(formData.next_pm_date).toLocaleDateString() : (pmSchedule.next_pm_date ? new Date(pmSchedule.next_pm_date).toLocaleDateString() : '-')}
                    </div>
                  )}
                  {!isEditing && formData.next_pm_date && (
                    <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Calculated based on last completion
                    </p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    No. of PMs
                  </label>
                  {isEditing ? (
                    <input
                      type="number"
                      name="no_of_pms"
                      value={formData.no_of_pms}
                      onChange={handleChange}
                      min="1"
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      placeholder="Enter number of PMs"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.no_of_pms || '-'}
                    </div>
                  )}
                  {isEditing && (
                    <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      End date will be auto-calculated based on start date, periodicity, and number of PMs
                    </p>
                  )}
                </div>
              </div>
            </div>

            {/* Assignment */}
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Assignment</h2>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Maintenance Team
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="maintenance_team"
                      value={formData.maintenance_team}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.maintenance_team || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Maintenance Manager
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="maintenance_manager"
                      value={formData.maintenance_manager}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.maintenance_manager || '-'}
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Assign To
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="assign_to"
                      value={formData.assign_to}
                      onChange={handleChange}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  ) : (
                    <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                      {pmSchedule.assign_to || '-'}
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Maintenance Entries */}
            {pmSchedule.maintenance_entries && pmSchedule.maintenance_entries.length > 0 && (
              <div>
                <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Maintenance Entries</h2>
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse border border-gray-300 dark:border-gray-600">
                    <thead>
                      <tr className="bg-gray-100 dark:bg-gray-700">
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          Asset
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          Asset Name
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          Manufacturer
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          Model
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          PM Start Date
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          PM End Date
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          Maintenance Log
                        </th>
                        <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                          Next PM Date
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {pmSchedule.maintenance_entries.map((entry: any, index: number) => {
                        // Find maintenance logs for this asset
                        const assetLogs = maintenanceLogs.filter(log => log.asset_name === entry.asset);
                        
                        // Calculate Next PM Date for this asset
                        const nextPMDate = calculateNextPMDateForAsset(
                          entry.asset,
                          pmSchedule.periodicity || 'Monthly',
                          pmSchedule.due_date || ''
                        );
                        
                        return (
                          <tr key={entry.name || index} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {entry.asset ? (
                                <button
                                  onClick={() => navigate(`/assets/${entry.asset}`)}
                                  className="text-blue-600 dark:text-blue-400 hover:underline"
                                >
                                  {entry.asset}
                                </button>
                              ) : '-'}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {entry.asset_name || '-'}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {entry.manufacturer || '-'}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {entry.model || '-'}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {entry.start_date ? new Date(entry.start_date).toLocaleDateString() : '-'}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {entry.end_date ? new Date(entry.end_date).toLocaleDateString() : '-'}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {assetLogs.length > 0 ? (
                                <div className="space-y-1">
                                  {assetLogs.map(log => (
                                    <button
                                      key={log.name}
                                      onClick={() => navigate(`/maintenance/${log.name}`)}
                                      className="block text-blue-600 dark:text-blue-400 hover:underline text-left"
                                      title={`Status: ${log.maintenance_status || 'N/A'} | Due: ${log.due_date ? new Date(log.due_date).toLocaleDateString() : 'N/A'}`}
                                    >
                                      {log.name}
                                    </button>
                                  ))}
                                  {assetLogs.length > 3 && (
                                    <span className="text-xs text-gray-500 dark:text-gray-400">
                                      +{assetLogs.length - 3} more
                                    </span>
                                  )}
                                </div>
                              ) : (
                                <span className="text-gray-400 dark:text-gray-500">No logs</span>
                              )}
                            </td>
                            <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                              {nextPMDate ? (
                                <span className="font-medium text-blue-600 dark:text-blue-400">
                                  {new Date(nextPMDate).toLocaleDateString()}
                                </span>
                              ) : (
                                <span className="text-gray-400 dark:text-gray-500">-</span>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Metadata */}
            <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
              <h2 className="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">Metadata</h2>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span className="text-gray-500 dark:text-gray-500">Created:</span>
                  <div className="font-medium text-gray-900 dark:text-white">
                    {pmSchedule.creation ? new Date(pmSchedule.creation).toLocaleString() : '-'}
                  </div>
                </div>
                <div>
                  <span className="text-gray-500 dark:text-gray-500">Created By:</span>
                  <div className="font-medium text-gray-900 dark:text-white">{pmSchedule.owner || '-'}</div>
                </div>
                <div>
                  <span className="text-gray-500 dark:text-gray-500">Modified:</span>
                  <div className="font-medium text-gray-900 dark:text-white">
                    {pmSchedule.modified ? new Date(pmSchedule.modified).toLocaleString() : '-'}
                  </div>
                </div>
                <div>
                  <span className="text-gray-500 dark:text-gray-500">Modified By:</span>
                  <div className="font-medium text-gray-900 dark:text-white">{pmSchedule.modified_by || '-'}</div>
                </div>
                {pmSchedule.amended_from && (
                  <div>
                    <span className="text-gray-500 dark:text-gray-500">Amended From:</span>
                    <div className="font-medium text-gray-900 dark:text-white">{pmSchedule.amended_from}</div>
                  </div>
                )}
                <div>
                  <span className="text-gray-500 dark:text-gray-500">Doc Status:</span>
                  <div className="font-medium text-gray-900 dark:text-white">
                    {pmSchedule.docstatus === 0 ? 'Draft' : pmSchedule.docstatus === 1 ? 'Submitted' : 'Cancelled'}
                  </div>
                </div>
                <div>
                  <span className="text-gray-500 dark:text-gray-500">IDX:</span>
                  <div className="font-medium text-gray-900 dark:text-white">{pmSchedule.idx || '-'}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {deleteConfirmOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 max-w-md">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">
              Confirm Delete
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-6">
              Are you sure you want to delete this PPM Planner? This action cannot be undone.
            </p>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeleteConfirmOpen(false)}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300"
                disabled={saving}
              >
                Cancel
              </button>
              <button
                onClick={handleDelete}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
                disabled={saving}
              >
                {saving ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PPMPlannerDetail;


