import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useIssueDetails, useIssueMutations } from '../hooks/useIssue';
import { 
  FaArrowLeft, 
  FaSave, 
  FaEdit, 
  FaTrash,
  FaCheckCircle,
  FaTimesCircle,
  FaExclamationTriangle,
  FaClock,
  FaUser,
  FaBuilding,
  FaEnvelope,
  FaCalendarAlt,
  FaTag,
  FaComment
} from 'react-icons/fa';
import { toast, ToastContainer, Bounce } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LinkField from '../components/LinkField';
import CommentSection from '../components/CommentSection';
import ActivityLog from '../components/ActivityLog';
import useDefaultHospital from '../hooks/useDefaultHospital';
import type { CreateIssueData } from '../services/issueService';

// Helper to get today's date in YYYY-MM-DD format
const getTodayDate = (): string => {
  return new Date().toISOString().split('T')[0];
};

// Helper to get current time in HH:MM:SS format
const getCurrentTime = (): string => {
  return new Date().toTimeString().split(' ')[0];
};

// Status badge styles
const getStatusStyle = (status: string) => {
  switch (status?.toLowerCase()) {
    case 'open':
      return { bg: 'bg-blue-100 dark:bg-blue-900/30', text: 'text-blue-800 dark:text-blue-300', border: 'border-blue-200 dark:border-blue-800' };
    case 'replied':
      return { bg: 'bg-purple-100 dark:bg-purple-900/30', text: 'text-purple-800 dark:text-purple-300', border: 'border-purple-200 dark:border-purple-800' };
    case 'on hold':
      return { bg: 'bg-yellow-100 dark:bg-yellow-900/30', text: 'text-yellow-800 dark:text-yellow-300', border: 'border-yellow-200 dark:border-yellow-800' };
    case 'resolved':
      return { bg: 'bg-green-100 dark:bg-green-900/30', text: 'text-green-800 dark:text-green-300', border: 'border-green-200 dark:border-green-800' };
    case 'closed':
      return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-800 dark:text-gray-300', border: 'border-gray-200 dark:border-gray-600' };
    default:
      return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-800 dark:text-gray-300', border: 'border-gray-200 dark:border-gray-600' };
  }
};

const IssueDetail: React.FC = () => {
  const { t } = useTranslation();
  const { issueName } = useParams<{ issueName: string }>();
  const navigate = useNavigate();
  
  const isNewIssue = issueName === 'new';
  
  // Form data state
  const [formData, setFormData] = useState<CreateIssueData & {
    opening_date?: string;
    opening_time?: string;
    first_responded_on?: string;
    resolution_date?: string;
    resolution_by?: string;
  }>({
    subject: '',
    raised_by: '',
    status: 'Open',
    priority: '',
    issue_type: '',
    description: '',
    contact: '',
    company: '',
    customer: '',
    project: '',
    resolution_details: '',
    opening_date: isNewIssue ? getTodayDate() : '',
    opening_time: isNewIssue ? getCurrentTime() : '',
    first_responded_on: '',
    resolution_date: '',
    resolution_by: '',
  });

  const { issue, loading, error, refetch } = useIssueDetails(isNewIssue ? null : issueName || null);
  const { createIssue, updateIssue, deleteIssue, loading: saving } = useIssueMutations();

  const [isEditing, setIsEditing] = useState(isNewIssue);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  useDefaultHospital(setFormData, {
    enabled: isNewIssue,
    fields: ['company'],
  });

  // Load issue data when fetched
  useEffect(() => {
    if (issue && !isNewIssue) {
      setFormData({
        subject: issue.subject || '',
        raised_by: issue.raised_by || '',
        status: issue.status || 'Open',
        priority: issue.priority || '',
        issue_type: issue.issue_type || '',
        description: issue.description || '',
        contact: issue.contact || '',
        company: issue.company || '',
        customer: issue.customer || '',
        project: issue.project || '',
        resolution_details: issue.resolution_details || '',
        opening_date: issue.opening_date || '',
        opening_time: issue.opening_time || '',
        first_responded_on: issue.first_responded_on ? issue.first_responded_on.split(' ')[0] : '',
        resolution_date: issue.resolution_date ? issue.resolution_date.split(' ')[0] : '',
        resolution_by: issue.resolution_by || '',
      });
      setIsEditing(false);
    }
  }, [issue, isNewIssue]);

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

  const handleSave = async () => {
    if (!formData.subject) {
      toast.error('Please enter a subject', {
        position: "top-right",
        autoClose: 4000,
        icon: <FaTimesCircle />
      });
      return;
    }

    try {
      if (isNewIssue) {
        const newIssue = await createIssue(formData);
        toast.success('Issue created successfully!', {
          position: "top-right",
          autoClose: 3000,
          icon: <FaCheckCircle />
        });
        navigate(`/support/${newIssue.name}`);
      } else {
        await updateIssue(issueName!, formData);
        toast.success('Issue updated successfully!', {
          position: "top-right",
          autoClose: 3000,
          icon: <FaCheckCircle />
        });
        setIsEditing(false);
        refetch();
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(`Failed to save: ${errorMessage}`, {
        position: "top-right",
        autoClose: 6000,
        icon: <FaTimesCircle />
      });
    }
  };

  const handleDelete = async () => {
    try {
      await deleteIssue(issueName!);
      toast.success('Issue deleted successfully!', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaCheckCircle />
      });
      navigate('/support');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(`Failed to delete: ${errorMessage}`, {
        position: "top-right",
        autoClose: 6000,
        icon: <FaTimesCircle />
      });
    }
  };

  const isFieldDisabled = useCallback((fieldname: string): boolean => {
    if (!isEditing) return true;
    // Some fields are always read-only
    if (['opening_date', 'opening_time'].includes(fieldname) && !isNewIssue) {
      return true;
    }
    return false;
  }, [isEditing, isNewIssue]);

  // Format datetime
  const formatDateTime = (dateStr: string) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading issue details...</p>
        </div>
      </div>
    );
  }

  if (error && !isNewIssue) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">Error Loading Issue</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error}</p>
          <button
            onClick={() => navigate('/support')}
            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded"
          >
            Back to Issues
          </button>
        </div>
      </div>
    );
  }

  const currentStatus = issue?.status || formData.status || 'Open';
  const statusStyle = getStatusStyle(currentStatus);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-4 sm:p-6 min-w-0 overflow-x-hidden">
      {/* Toast Container */}
      <ToastContainer
        position="top-right"
        autoClose={4000}
        hideProgressBar={false}
        newestOnTop
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="colored"
        transition={Bounce}
      />

      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between lg:items-center flex-wrap">
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate('/support')}
            className="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
          >
            <FaArrowLeft size={20} />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center gap-3">
              {isNewIssue ? t('issues.newIssue') : issue?.name || t('issues.issueDetails')}
              {!isNewIssue && (
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${statusStyle.bg} ${statusStyle.text} ${statusStyle.border} border`}>
                  {currentStatus}
                </span>
              )}
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              {isNewIssue ? t('issues.createNewIssue') : formData.subject}
            </p>
          </div>
        </div>

        <div className="flex gap-3">
          {!isNewIssue && !isEditing && (
            <>
              <button
                onClick={() => setIsEditing(true)}
                className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"
              >
                <FaEdit />
                {t('common.edit')}
              </button>
              <button
                onClick={() => setShowDeleteConfirm(true)}
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"
              >
                <FaTrash />
                {t('common.delete')}
              </button>
            </>
          )}
          {isEditing && (
            <>
              <button
                onClick={() => {
                  if (isNewIssue) {
                    navigate('/support');
                  } else {
                    setIsEditing(false);
                    refetch();
                  }
                }}
                className="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg"
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50"
              >
                <FaSave />
                {saving ? t('common.saving') : t('common.save')}
              </button>
            </>
          )}
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <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 p-6 max-w-md w-full mx-4 shadow-xl">
            <div className="flex items-start gap-3 mb-4">
              <FaExclamationTriangle className="text-red-500 text-xl mt-0.5" />
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Delete Issue</h3>
                <p className="text-gray-600 dark:text-gray-400 mt-1">
                  Are you sure you want to delete this issue? This action cannot be undone.
                </p>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="px-4 py-2 bg-gray-300 hover:bg-gray-400 text-gray-700 rounded-lg"
              >
                Cancel
              </button>
              <button
                onClick={handleDelete}
                disabled={saving}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg disabled:opacity-50"
              >
                {saving ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Form */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content - Left Column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Issue Details */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaComment className="text-blue-500" />
              {t('issues.issueDetails')}
            </h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t('issues.subject')} <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  name="subject"
                  value={formData.subject}
                  onChange={handleChange}
                  disabled={isFieldDisabled('subject')}
                  placeholder={t('issues.enterSubject')}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <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-1">
                    {t('commonFields.status')}
                  </label>
                  <select
                    name="status"
                    value={formData.status}
                    onChange={handleChange}
                    disabled={isFieldDisabled('status')}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="Open">Open</option>
                    <option value="Replied">Replied</option>
                    <option value="On Hold">On Hold</option>
                    <option value="Resolved">Resolved</option>
                    <option value="Closed">Closed</option>
                  </select>
                </div>

                <div>
                  <LinkField
                    label={t('commonFields.priority')}
                    doctype="Issue Priority"
                    value={formData.priority || ''}
                    onChange={(val) => setFormData({ ...formData, priority: val })}
                    disabled={isFieldDisabled('priority')}
                    placeholder={t('issues.selectPriority')}
                  />
                </div>
              </div>

              <div>
                <LinkField
                  label={t('issues.issueType')}
                  doctype="Issue Type"
                  value={formData.issue_type || ''}
                  onChange={(val) => setFormData({ ...formData, issue_type: val })}
                  disabled={isFieldDisabled('issue_type')}
                  placeholder={t('issues.selectIssueType')}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t('commonFields.description')}
                </label>
                <textarea
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  disabled={isFieldDisabled('description')}
                  placeholder={t('issues.describeIssue')}
                  rows={5}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                />
              </div>
            </div>
          </div>

          {/* Contact Information */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaUser className="text-green-500" />
              {t('issues.contactInformation')}
            </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-1">
                  {t('issues.raisedBy')}
                </label>
                <div className="relative">
                  <FaEnvelope className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                  <input
                    type="email"
                    name="raised_by"
                    value={formData.raised_by}
                    onChange={handleChange}
                    disabled={isFieldDisabled('raised_by')}
                    placeholder={t('common.email')}
                    className="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Contact Name
                </label>
                <input
                  type="text"
                  name="contact"
                  value={formData.contact}
                  onChange={handleChange}
                  disabled={isFieldDisabled('contact')}
                  placeholder="Contact person name"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div> */}

              <div>
                <LinkField
                  label={t('commonFields.company')}
                  doctype="Company"
                  value={formData.company || ''}
                  onChange={(val) => setFormData({ ...formData, company: val })}
                  disabled={isFieldDisabled('company')}
                  placeholder={t('issues.selectCompany')}
                />
              </div>

              {/* <div>
                <LinkField
                  label="Customer"
                  doctype="Customer"
                  value={formData.customer || ''}
                  onChange={(val) => setFormData({ ...formData, customer: val })}
                  disabled={isFieldDisabled('customer')}
                  placeholder="Select customer"
                />
              </div>

              <div>
                <LinkField
                  label="Project"
                  doctype="Project"
                  value={formData.project || ''}
                  onChange={(val) => setFormData({ ...formData, project: val })}
                  disabled={isFieldDisabled('project')}
                  placeholder="Select project"
                />
              </div> */}
            </div>
          </div>

          {/* Resolution */}
          {!isNewIssue && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
                <FaCheckCircle className="text-purple-500" />
                {t('issues.resolution')}
              </h2>
              
              <div className="space-y-4">
                <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-1">
                      {t('issues.firstRespondedOn')}
                    </label>
                    <input
                      type="date"
                      name="first_responded_on"
                      value={formData.first_responded_on || ''}
                      onChange={handleChange}
                      disabled={isFieldDisabled('first_responded_on')}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      {t('issues.resolutionDate')}
                    </label>
                    <input
                      type="date"
                      name="resolution_date"
                      value={formData.resolution_date || ''}
                      onChange={handleChange}
                      disabled={isFieldDisabled('resolution_date')}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                </div>

                <div>
                  <LinkField
                    label={t('issues.resolvedBy')}
                    doctype="User"
                    value={formData.resolution_by || ''}
                    onChange={(val) => setFormData({ ...formData, resolution_by: val })}
                    disabled={isFieldDisabled('resolution_by')}
                    placeholder={t('maintenance.selectUser')}
                  />
                </div>

                <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('issues.resolutionDetails')}
                  </label>
                  <textarea
                    name="resolution_details"
                    value={formData.resolution_details}
                    onChange={handleChange}
                    disabled={isFieldDisabled('resolution_details')}
                    placeholder={t('issues.describeResolution')}
                    rows={4}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Sidebar - Right Column */}
        <div className="space-y-6">
          {/* Status Card */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaTag className="text-orange-500" />
              {t('issues.statusInformation')}
            </h2>
            
            <div className="space-y-4">
              <div className={`p-4 rounded-lg border ${statusStyle.bg} ${statusStyle.border}`}>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('issues.currentStatus')}</p>
                <p className={`text-xl font-semibold ${statusStyle.text}`}>
                  {currentStatus}
                </p>
              </div>

              {formData.priority && (
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('commonFields.priority')}</p>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {formData.priority}
                  </p>
                </div>
              )}

              {formData.issue_type && (
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('issues.issueType')}</p>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {formData.issue_type}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Timeline Card */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaCalendarAlt className="text-teal-500" />
              {t('issues.timeline')}
            </h2>
            
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('issues.openingDate')}</p>
                <p className="text-sm text-gray-900 dark:text-white">
                  {formData.opening_date || '-'}
                </p>
              </div>

              <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Opening Time</p>
                <p className="text-sm text-gray-900 dark:text-white">
                  {formData.opening_time || '-'}
                </p>
              </div>

              {!isNewIssue && issue && (
                <>
                  <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                    <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Created</p>
                    <p className="text-sm text-gray-900 dark:text-white">
                      {formatDateTime(issue.creation)}
                    </p>
                  </div>
                </>
              )}
            </div>
          </div>

          {!isNewIssue && (
            <div className="space-y-6">
              <CommentSection
                referenceDoctype="Issue"
                referenceName={issueName || null}
                title="Comments & Discussion"
                pollInterval={30000}
                initialLimit={5}
              />
              <ActivityLog
                doctype="Issue"
                docname={issueName || null}
                creationDate={issue?.creation}
                createdBy={issue?.owner}
                initialVisible={5}
                startCollapsed={true}
              />
            </div>
          )}

          {/* Company Info Card */}
          {formData.company && !isNewIssue && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
                <FaBuilding className="text-indigo-500" />
                Company
              </h2>
              
              <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-sm font-medium text-gray-900 dark:text-white">
                  {formData.company}
                </p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default IssueDetail;