import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { FormattedDescription } from '@/components/common/FormattedDescription';
import { Loader2, ArrowLeft, FileText, CheckCircle, XCircle, Clock } from 'lucide-react';
import { getSummaryDetails, markAsViewed, type SummaryDetails } from '@/services/summaryApi';
import { format } from 'date-fns';
import { toast } from 'sonner';

export function SharedSummaryDetail() {
  const { sharedSummaryId } = useParams<{ sharedSummaryId: string }>();
  const navigate = useNavigate();
  const [summary, setSummary] = useState<SummaryDetails | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!sharedSummaryId) {
      navigate('/shared-summaries');
      return;
    }

    const fetchSummary = async () => {
      try {
        setLoading(true);
        // First, mark as viewed
        try {
          await markAsViewed(sharedSummaryId);
        } catch (error) {
          console.warn('Failed to mark as viewed:', error);
        }
        // Then get the summary details
        // Note: We need to get the summaryId from the shared summary first
        // For now, we'll use the sharedSummaryId to get details
        // The backend should handle this, but we might need to adjust the API
        const details = await getSummaryDetails(sharedSummaryId);
        setSummary(details);
      } catch (error: any) {
        console.error('Failed to fetch summary details:', error);
        toast.error(error?.response?.data?.message || 'Failed to load summary');
        navigate('/shared-summaries');
      } finally {
        setLoading(false);
      }
    };

    fetchSummary();
  }, [sharedSummaryId, navigate]);

  const getStatusIcon = (status: string) => {
    const statusLower = status.toLowerCase();
    if (statusLower === 'approved') return <CheckCircle className="h-4 w-4 text-green-600" />;
    if (statusLower === 'rejected') return <XCircle className="h-4 w-4 text-red-600" />;
    if (statusLower === 'pending' || statusLower === 'in progress') return <Clock className="h-4 w-4 text-orange-600" />;
    return <FileText className="h-4 w-4 text-gray-600" />;
  };

  const getStatusColor = (status: string) => {
    const statusLower = status.toLowerCase();
    if (statusLower === 'approved') return 'bg-green-100 text-green-700 border-green-300';
    if (statusLower === 'rejected') return 'bg-red-100 text-red-700 border-red-300';
    if (statusLower === 'pending' || statusLower === 'in progress') return 'bg-orange-100 text-orange-700 border-orange-300';
    return 'bg-gray-100 text-gray-700 border-gray-300';
  };

  // Helper function to get designation or department (fallback to department if designation is N/A or empty)
  const getDesignationOrDepartment = (designation?: string | null, department?: string | null) => {
    if (designation && designation.trim() && designation.trim().toUpperCase() !== 'N/A') {
      return designation;
    }
    if (department && department.trim() && department.trim().toUpperCase() !== 'N/A') {
      return department;
    }
    return 'N/A';
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-12 w-12 animate-spin text-blue-600 mx-auto mb-4" />
          <p className="text-gray-600">Loading summary...</p>
        </div>
      </div>
    );
  }

  if (!summary) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <FileText className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Summary Not Found</h2>
          <p className="text-gray-600 mb-4">The summary you're looking for doesn't exist.</p>
          <Button onClick={() => navigate('/shared-summaries')}>Go Back</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4 sm:p-6">
      <div className="max-w-5xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => navigate('/shared-summaries')}
            className="mb-4"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Shared Summaries
          </Button>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">Request Summary</h1>
        </div>

        {/* Summary Card */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 mb-6">
          <div className="p-6 border-b border-gray-200">
            <div className="flex items-start justify-between gap-4 mb-4">
              <div>
                <h2 className="text-xl font-semibold text-gray-900 mb-2">{summary.title}</h2>
                <p className="text-sm text-gray-600">Request #{summary.requestNumber}</p>
              </div>
              <Badge className={getStatusColor(summary.workflow.status)}>
                {getStatusIcon(summary.workflow.status)}
                <span className="ml-1 capitalize">{summary.workflow.status}</span>
              </Badge>
            </div>
            {summary.description && (
              <div className="mb-4">
                <FormattedDescription 
                  content={summary.description} 
                  className="text-gray-700"
                />
              </div>
            )}
          </div>

          {/* Initiator Section */}
          <div className="p-6 border-b border-gray-200">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Initiator</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div>
                <p className="text-xs text-gray-500 mb-1">Name</p>
                <p className="text-sm font-medium text-gray-900">{summary.initiator.name}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500 mb-1">Designation</p>
                <p className="text-sm font-medium text-gray-900">{getDesignationOrDepartment(summary.initiator.designation, summary.initiator.department)}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500 mb-1">Status</p>
                <p className="text-sm font-medium text-gray-900">{summary.initiator.status}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500 mb-1">Time Stamp</p>
                <p className="text-sm font-medium text-gray-900">
                  {format(new Date(summary.initiator.timestamp), 'MMM dd, yy, HH:mm')}
                </p>
              </div>
            </div>
            {/* Initiator remarks commented out - remarks won't come while initiating */}
            {/* <div className="mt-4">
              <p className="text-xs text-gray-500 mb-1">Remarks by Concern</p>
              <p className="text-sm text-gray-700">{summary.initiator.remarks}</p>
            </div> */}
          </div>

          {/* Approvers Section */}
          {summary.approvers && summary.approvers.length > 0 && (
            <div className="p-6 border-b border-gray-200">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Workflow</h3>
              {summary.approvers.map((approver, index) => (
                <div key={index} className="mb-6 last:mb-0">
                  <h4 className="text-md font-semibold text-gray-800 mb-3">
                    Approver {approver.levelNumber}
                  </h4>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-3">
                    <div>
                      <p className="text-xs text-gray-500 mb-1">Name</p>
                      <p className="text-sm font-medium text-gray-900">{approver.name}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 mb-1">Designation</p>
                      <p className="text-sm font-medium text-gray-900">{getDesignationOrDepartment(approver.designation, approver.department)}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 mb-1">Status</p>
                      <div className="flex items-center gap-1">
                        {getStatusIcon(approver.status)}
                        <p className="text-sm font-medium text-gray-900">{approver.status}</p>
                      </div>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 mb-1">Time Stamp</p>
                      <p className="text-sm font-medium text-gray-900">
                        {format(new Date(approver.timestamp), 'MMM dd, yy, HH:mm')}
                      </p>
                    </div>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 mb-1">Remarks</p>
                    <p className="text-sm text-gray-700">{approver.remarks}</p>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Closing Remarks Section */}
          <div className="p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Closing Remarks (Conclusion)</h3>
            <div className="bg-gray-50 rounded-lg p-4">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                <div>
                  <p className="text-xs text-gray-500 mb-1">Name</p>
                  <p className="text-sm font-medium text-gray-900">{summary.initiator.name}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500 mb-1">Designation</p>
                  <p className="text-sm font-medium text-gray-900">{getDesignationOrDepartment(summary.initiator.designation, summary.initiator.department)}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500 mb-1">Status</p>
                  <p className="text-sm font-medium text-gray-900">Concluded</p>
                </div>
                {summary.isAiGenerated && (
                  <div>
                    <p className="text-xs text-gray-500 mb-1">Source</p>
                    <Badge variant="outline" className="text-xs">AI Generated</Badge>
                  </div>
                )}
              </div>
              <div>
                <p className="text-xs text-gray-500 mb-1">Remarks</p>
                {summary.closingRemarks ? (
                  <FormattedDescription 
                    content={summary.closingRemarks} 
                    className="text-sm text-gray-700"
                  />
                ) : (
                  <p className="text-sm text-gray-700">—</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

