import React, { useState, useEffect , useCallback } from 'react';
import { 
  FileText, 
  FileVideo,
  Upload, 
  Send, 
  Clock, 
  CheckCircle, 
  AlertCircle,
  Filter,
  Search,
  Calendar,
  User,
  MapPin,
  Phone,
  Mail,
  Camera,
  Mic,
  PaperclipIcon,
  Star,
  MessageCircle,
  Trash2,
  Edit3,
  Eye,
  ListPlus,
  FileAudio,
  Paperclip,
  Loader2,
  X,
  Video
} from 'lucide-react';
import axios from 'axios';
import Footer from '../components/Footer';

const API_BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;


const initialStats = {
  total_complaints: 0,
  received_complaints: 0,
  pending_complaints: 0,
  closed_complaints: 0,
};

export default function Complaints() {
  const [activeTab, setActiveTab] = useState('file');
  const [stats, setStats] = useState(initialStats);
  const [selectedCategory, setSelectedCategory] = useState('');
  const [priority, setPriority] = useState('medium');
  const [attachments, setAttachments] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [user, setUser] = useState(null);
  const [categories, setCategories] = useState([]);
  const [statsRefreshKey, setStatsRefreshKey] = useState(0);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [activeView, setActiveView] = useState('new'); // State to control view (new/previous)
  const [formData, setFormData] = useState({
    category: '',
    short_description: '',
    complaint_text: '',
  });
  const [audioFile, setAudioFile] = useState(null);
  const [videoFile, setVideoFile] = useState(null);
  
  const [success, setSuccess] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [complaintsList, setComplaintsList] = useState([]);
  const [isListLoading, setIsListLoading] = useState(true);
  const [listError, setListError] = useState(null);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
    if (error) setError(null);
  };

  const handleAudioFileChange = (e) => {
    const file = e.target.files[0];
    if (file && file.size > 10 * 1024 * 1024) {
      setError("Audio file size must be less than 10MB");
      setAudioFile(null); // Clear file if too large
      return;
    }
    setAudioFile(file);
    if (error) setError(null);
  };

  const triggerStatsRefresh = () => {
    setStatsRefreshKey(prevKey => prevKey + 1);
};
  

  const handleVideoFileChange = (e) => {
    const file = e.target.files[0];
    if (file && file.size > 50 * 1024 * 1024) {
      setError("Video file size must be less than 50MB");
      setVideoFile(null); // Clear file if too large
      return;
    }
    setVideoFile(file);
    if (error) setError(null);
  };

  const removeAudioFile = () => setAudioFile(null);
  const removeVideoFile = () => setVideoFile(null);

  const handleViewChange = (view) => {
    setActiveView(view);
    setError(null);
    setSuccess(null);
    if (view === "previous" && auth?.user) { // Use auth?.user or whatever your context provides
      
    }
  };


  useEffect(() => {
    const fetchCategories = async () => {
        setIsLoading(true);
        setError(null);

        const accessToken = localStorage.getItem("accessToken");
        if (!accessToken) {
            // No need to set categories to [] since the initial state is []
            setError("You must be logged in to access complaint categories.");
            setIsLoading(false);
            return;
        }

        try {
            const categoriesRes = await fetch(`${API_BASE_URL}/complaints/categories/`, {
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${accessToken}`,
                },
            });

            if (!categoriesRes.ok) throw new Error("Failed to load categories");
            
            const categoriesData = await categoriesRes.json();
            setCategories(categoriesData);

        } catch (err) {
            // Use a specific message or fall back to the generic one
            const errorMsg = err.message || "Failed to load categories. Please check your network.";
            setError(errorMsg);
            setCategories([]); // Clear categories on failure
        } finally {
            setIsLoading(false);
        }
    };

    fetchCategories();
}, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);
    setSuccess(null);
    setUploadProgress(0);

    const accessToken = localStorage.getItem("accessToken");
    if (!accessToken) {
        setIsSubmitting(false);
        setError("You must be logged in to file a complaint.");
        return;
    }
    
    // Simple client-side validation for required fields
    if (!formData.category || !formData.short_description) {
        setIsSubmitting(false);
        setError("Please fill in all required fields (Category and Short Description).");
        return;
    }

    const formDataPayload = new FormData();
    formDataPayload.append("category", formData.category);
    formDataPayload.append("short_description", formData.short_description);
    formDataPayload.append("complaint_text", formData.complaint_text);
    

    if (audioFile) formDataPayload.append("complaint_audio", audioFile);
    if (videoFile) formDataPayload.append("complaint_video", videoFile);

    try {
      // Use Axios for better control over progress and cancellation (if needed)
      // The manual progress interval simulation is now removed, but can be added back 
      // using the axios `onUploadProgress` config if you need a real progress bar.
      
      // Simulating progress start
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => Math.min(prev + 10, 90));
      }, 200);

      const response = await fetch(`${API_BASE_URL}/complaints/citizen-complaint/`, {
        method: "POST",
        headers: { "Authorization": `Bearer ${accessToken}` },
        body: formDataPayload,
      });
      

      if (!response.ok) throw new Error("Failed to submit complaint. Please try again.");
      // Stop progress simulation/cleanup
      clearInterval(progressInterval);
      setUploadProgress(100); 

      // Axios throws error on non-2xx status, so check is simplified
      const newComplaint = response.data;

      setFormData({ category: "", short_description: "", complaint_text: "" });
      setAudioFile(null);
      setVideoFile(null);
      setUploadProgress(0);
      setSuccess("Complaint submitted successfully! We'll review it shortly.");

      setTimeout(() => {
        setSuccess(null);
        setActiveView("previous");
        
      }, 2000);
      setStatsRefreshKey(prevKey => prevKey + 1);

    } catch (err) {
      clearInterval(progressInterval);
      const msg = err.response?.data?.detail || err.message || "Failed to submit complaint. Please check the network and try again.";
      setError(msg);
      setUploadProgress(0);
    } finally {
      setIsSubmitting(false);
    }
  };

  const fetchComplaintStats = async () => {
    // You need to replace this with your actual token retrieval logic (e.g., from localStorage, context, or Redux)
    const accessToken = localStorage.getItem("accessToken"); // Example: retrieving JWT access token
    
    if (!accessToken) {
        setError("User not authenticated. Please log in.");
        setIsLoading(false);
        return;
    }

    try {
        const response = await axios.get(`${API_BASE_URL}/complaints/user-stats/`, {
            headers: {
                // Assuming you are using JWT, the header is usually "Bearer <token>"
                'Authorization': `Bearer ${accessToken}` 
            }
        });
        // Update the state with the fetched data
        setStats(response.data);
        setError(null);
    } catch (err) {
      const errorMsg = err.message || "Failed to load statistics. Please check your network.";
      setError(errorMsg);
        // Reset to initial state on error
        setStats(initialStats); 
    } finally {
        setIsLoading(false);
    }
};

const fetchComplaints = useCallback(async () => {
  const accessToken = localStorage.getItem("accessToken");
  
  if (!accessToken) {
      setListError("User not authenticated for list retrieval.");
      setIsListLoading(false);
      return;
  }

  setIsListLoading(true);
  try {
      // NOTE: The endpoint is '/complaints/citizen-complaint/list/' based on your urls.py
      const response = await axios.get(`${API_BASE_URL}/complaints/citizen-complaint/list/`, {
          headers: {
              'Authorization': `Bearer ${accessToken}`
          }
      });
      // The response.data will be the array of complaints
      setComplaintsList(response.data);
      setListError(null);
  } catch (err) {
      console.error('Error fetching complaints list:', err);
      const errorMsg = err.response?.data?.detail || "Failed to load complaints list.";
      setListError(errorMsg);
      setComplaintsList([]);
  } finally {
      setIsListLoading(false);
  }
}, []);

// useEffect hook to call the fetching function when the component mounts
useEffect(() => {
    fetchComplaintStats();
}, [fetchComplaintStats, statsRefreshKey]); // Empty dependency array ensures it runs only once on mount


useEffect(() => {
  fetchComplaints();
  // Since the list might update after submission, you might want to link this to your statsRefreshKey
}, [fetchComplaints, statsRefreshKey]);


const overallLoading = isLoading || isListLoading;
const overallError = error || listError;

if (overallLoading) {
  
  return <p className="p-4 text-center text-blue-600">Loading dashboard and complaints...</p>;
}

if (overallError) {
  
  return (
      <div className="p-4 text-red-500 border border-red-300 bg-red-50">
          <p>An error occurred: {overallError}</p>
          <p className="text-sm">Please try logging in again or refresh the page.</p>
      </div>
  );
}


const displayComplaints = complaintsList; 
    
    // If no complaints are found
if (displayComplaints.length === 0) {
        return <p className="text-gray-600 p-4">You have not submitted any complaints yet.</p>;
    }

  const handleFileUpload = (event) => {
    const files = Array.from(event.target.files);
    setAttachments(prev => [...prev, ...files]);
  };

  const removeAttachment = (index) => {
    setAttachments(prev => prev.filter((_, i) => i !== index));
  };

  
  const renderFileUploadCard = (file, type, onRemove, IconComponent) => (
    <div className="flex items-center justify-between bg-white p-3 border border-gray-200 rounded-lg shadow-sm">
      <div className="flex items-center space-x-3">
        <IconComponent className="w-5 h-5 text-blue-600" />
        <div>
          <span className="text-sm font-medium text-gray-700 block truncate max-w-xs">{file.name}</span>
          <span className="text-xs text-gray-500 block">
            {(file.size / 1024 / 1024).toFixed(2)} MB
          </span>
        </div>
      </div>
      <button
        type="button"
        onClick={onRemove}
        className="text-red-500 hover:text-red-700 p-1 rounded-full hover:bg-red-50 transition-colors"
        title={`Remove ${type}`}
      >
        <Trash2 className="w-4 h-4" />
      </button>
    </div>
  );

  return (
    <div className="min-h-screen bg-gray-100">
      {/* Hero Section */}
      <div className="bg-gradient-to-r from-blue-800 to-blue-900 text-white py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <h1 className="text-3xl md:text-4xl font-bold mb-3">
              Citizen Complaints Portal
            </h1>
            <p className="text-lg text-blue-100 max-w-2xl mx-auto">
              Report issues, track progress, and help us build a better community together.
            </p>
          </div>
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="bg-white border-b border-gray-200 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex space-x-8">
            <button
              onClick={() => setActiveTab('file')}
              className={`py-3 px-2 border-b-3 font-semibold text-sm transition-colors ${
                activeTab === 'file'
                  ? 'border-blue-600 text-blue-600 bg-blue-50'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'
              }`}
            >
              <FileText className="w-5 h-5 inline mr-2" />
              File Complaint
            </button>
            <button
              onClick={() => setActiveTab('track')}
              className={`py-3 px-2 border-b-3 font-semibold text-sm transition-colors ${
                activeTab === 'track'
                  ? 'border-blue-600 text-blue-600 bg-blue-50'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'
              }`}
            >
              <Clock className="w-5 h-5 inline mr-2" />
              Track Complaints
            </button>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* File Complaint Tab */}
        {activeTab === 'file' && (
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
            {/* Main Form */}
            <div className="lg:col-span-3">
              <div className="bg-white border border-gray-200 p-6">
                <div className="flex items-center mb-5 pb-4 border-b border-gray-200">
                  <div className="bg-blue-600 p-2 mr-3">
                    <FileText className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold text-gray-900">File a New Complaint</h2>
                    <p className="text-gray-600 text-sm">Fill out the form below to report your issue</p>
                  </div>
                </div>

                <form onSubmit={handleSubmit} className="space-y-6">

                  {/* Success Message Display */}
{success && (
    <div className="p-4 bg-green-100 border-l-4 border-green-500 text-green-700 rounded-lg shadow-sm flex items-center">
        {/* You'll need to import CheckCircle (or similar) from your icon library */}
        <CheckCircle className="w-5 h-5 mr-3 flex-shrink-0" />
        <p className="font-medium">{success}</p>
        <button
            type="button"
            onClick={() => setSuccess(null)}
            className="ml-auto text-green-700 hover:text-green-900 focus:outline-none"
        >
            <X className="w-4 h-4" /> {/* X icon for closing */}
        </button>
    </div>
)}

    {/* Error Message Display (Good practice to show here too) */}
{error && (
    <div className="p-4 bg-red-100 border-l-4 border-red-500 text-red-700 rounded-lg shadow-sm flex items-center">
        <AlertTriangle className="w-5 h-5 mr-3 flex-shrink-0" />
        <p className="font-medium">{error}</p>
    </div>
)}
       

          {/* Complaint Details Section */}
          <div className="bg-white border-l-4 border-red-500 p-4 shadow-sm">
            <h3 className="text-lg font-semibold text-white mb-4 flex items-center bg-red-500 p-2 -m-4 -mx-4">
              <AlertCircle className="w-5 h-5 mr-2 text-white" />
              Complaint Details
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Inside the Category Select div */}
<div>
    <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-1">
        Category *
    </label>
    <select
        id="category"
        name="category"
        value={formData.category}
        onChange={handleInputChange}
        required
        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
        disabled={isLoading || categories.length === 0} // Disable while loading
    >
        {/* Conditional Options */}
        {isLoading && (
            <option value="" disabled>Loading categories...</option>
        )}
        {!isLoading && categories.length === 0 && (
            <option value="" disabled>No categories available</option>
        )}
        {!isLoading && categories.length > 0 && (
            <option value="">Select a category</option>
        )}
        
        {/* Map the fetched categories */}
        {categories.map((cat) => (
            <option key={cat.category_id} value={cat.category_id}> 
                {cat.name}
            </option>
        ))}
    </select>
</div>
              {/* Short Description (Title) */}
              <div>
                <label htmlFor="short_description" className="block text-sm font-medium text-gray-700 mb-1">
                  Short Description *
                </label>
                <input
                  id="short_description"
                  name="short_description"
                  type="text"
                  value={formData.short_description}
                  onChange={handleInputChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                  placeholder="Brief summary of the issue"
                />
              </div>
            </div>

            {/* Detailed Description */}
            <div className="mt-4">
              <label htmlFor="complaint_text" className="block text-sm font-medium text-gray-700 mb-1">
                Detailed Description
              </label>
              <textarea
                id="complaint_text"
                name="complaint_text"
                rows={4}
                value={formData.complaint_text}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                placeholder="Provide detailed information about your complaint..."
              />
            </div>
          </div>

          {/* File Attachments Section */}
          <div className="bg-white border-l-4 border-green-500 p-4 shadow-sm">
            <h3 className="text-lg font-semibold text-white mb-4 flex items-center bg-green-500 p-2 -m-4 -mx-4">
              <Paperclip className="w-5 h-5 mr-2 text-white" />
              Attachments (Optional)
            </h3>

            {/* File Upload Buttons */}
            <div className="flex gap-4 mb-4">
              {/* Audio Upload Button */}
              <label className="cursor-pointer flex-1">
                <input
                  type="file"
                  accept="audio/*"
                  onChange={handleAudioFileChange}
                  className="hidden"
                />
                <div className="border-2 border-dashed border-gray-300 p-4 text-center rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-all font-medium text-gray-700">
                  <Mic className="w-6 h-6 text-gray-500 mx-auto mb-1" />
                  <p className="text-sm">Add Audio (Max 10MB)</p>
                </div>
              </label>

              {/* Video Upload Button */}
              <label className="cursor-pointer flex-1">
                <input
                  type="file"
                  accept="video/*"
                  onChange={handleVideoFileChange}
                  className="hidden"
                />
                <div className="border-2 border-dashed border-gray-300 p-4 text-center rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-all font-medium text-gray-700">
                  <Upload className="w-6 h-6 text-gray-500 mx-auto mb-1" />
                  <p className="text-sm">Add Video (Max 50MB)</p>
                </div>
              </label>
            </div>

            {/* Display Attached Files (uses renderFileUploadCard helper) */}
            <div className="space-y-2">
              {audioFile &&
                renderFileUploadCard(audioFile, "audio", removeAudioFile, FileAudio)}
              {videoFile &&
                renderFileUploadCard(videoFile, "video", removeVideoFile, FileVideo)}
            </div>
          </div>

          {/* Submission Progress Bar */}
          {isSubmitting && uploadProgress > 0 && (
            <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-sm font-medium text-blue-700 mb-1">
                Uploading... {uploadProgress}%
              </p>
              <div className="w-full bg-gray-200 rounded-full h-2.5">
                <div
                  className="bg-blue-600 h-2.5 rounded-full transition-all duration-500 ease-out"
                  style={{ width: `${uploadProgress}%` }}
                ></div>
              </div>
            </div>
          )}

          {/* Submit Button */}
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            {/* The "Save as Draft" button from your snippet is not fully implemented here
                but kept for structure. */}
            <button
              type="button"
              className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-all"
            >
              Save as Draft
            </button>

            <button
              type="submit"
              disabled={isSubmitting || !formData.category || !formData.short_description}
              className={`px-6 py-3 rounded-lg text-white font-semibold transition-all flex items-center shadow-md ${
                isSubmitting ? 'bg-blue-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700'
              }`}
            >
              {isSubmitting ? (
                <Loader2 className="w-5 h-5 mr-2 animate-spin" />
              ) : (
                <Send className="w-5 h-5 mr-2" />
              )}
              {isSubmitting ? "Submitting..." : "Submit Complaint"}
            </button>
          </div>
        </form>
              </div>
            </div>

            {/* Sidebar */}
            <div className="space-y-4">
              {/* Quick Tips */}
              <div className="bg-blue-50 border border-blue-200 p-4">
                <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                  <Star className="w-5 h-5 mr-2 text-yellow-500" />
                  Quick Tips
                </h3>
                <ul className="space-y-2 text-sm text-gray-600">
                  <li className="flex items-start">
                    <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-2 mr-2 flex-shrink-0" />
                    Provide specific location details
                  </li>
                  <li className="flex items-start">
                    <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-2 mr-2 flex-shrink-0" />
                    Include photos or videos when possible
                  </li>
                  <li className="flex items-start">
                    <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-2 mr-2 flex-shrink-0" />
                    Use clear, descriptive titles
                  </li>
                  <li className="flex items-start">
                    <div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-2 mr-2 flex-shrink-0" />
                    Check existing complaints to avoid duplicates
                  </li>
                </ul>
              </div>

              {/* Contact Information */}
              <div className="bg-white border border-gray-200 p-4">
                <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                  <MessageCircle className="w-5 h-5 mr-2 text-green-500" />
                  Need Help?
                </h3>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center text-gray-600">
                    <Phone className="w-4 h-4 mr-2 text-blue-500" />
                    +1 (555) 123-4567
                  </div>
                  <div className="flex items-center text-gray-600">
                    <Mail className="w-4 h-4 mr-2 text-blue-500" />
                    support@rps.gov
                  </div>
                  <div className="flex items-center text-gray-600">
                    <Clock className="w-4 h-4 mr-2 text-blue-500" />
                    Mon-Fri: 9AM-6PM
                  </div>
                </div>
              </div>

              {/* Recent Activity */}
              <div className="bg-white border border-gray-200 p-4">
                <h3 className="text-lg font-semibold text-gray-900 mb-3">Recent Activity</h3>
                <div className="space-y-2">
                  <div className="flex items-center text-sm">
                    <div className="w-2 h-2 bg-green-400 rounded-full mr-2" />
                    <span className="text-gray-600">15 complaints resolved today</span>
                  </div>
                  <div className="flex items-center text-sm">
                    <div className="w-2 h-2 bg-blue-400 rounded-full mr-2" />
                    <span className="text-gray-600">23 new complaints filed</span>
                  </div>
                  <div className="flex items-center text-sm">
                    <div className="w-2 h-2 bg-yellow-400 rounded-full mr-2" />
                    <span className="text-gray-600">8 complaints in progress</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Track Complaints Tab */}
        {activeTab === 'track' && (
          <div>
            {/* Search and Filter Bar */}
            <div className="bg-white border border-gray-200 p-4 mb-6">
              <div className="flex flex-col md:flex-row gap-3">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-2 w-4 h-4 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search complaints..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-9 pr-3 py-2 border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                  />
                </div>
                <div className="flex gap-3">
                  <select
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                    className="px-3 py-2 border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                  >
                    <option value="all">All Status</option>
                    <option value="pending">Pending</option>
                    <option value="in-progress">In Progress</option>
                    <option value="resolved">Resolved</option>
                  </select>
                  <button className="px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 transition-all flex items-center">
                    <Filter className="w-4 h-4 mr-1" />
                    Filter
                  </button>
                </div>
              </div>
            </div>

            {/* Statistics Cards */}
            <div className="grid grid-cols-4 gap-4 mb-6">
            {/* Total Complaints Card */}
            <div className="bg-blue-600 text-white p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <p className="text-blue-100 text-xs">Total Complaints</p>
                        <p className="text-2xl font-bold">{stats.total_complaints}</p> {/* Dynamic Value */}
                    </div>
                    <FileText className="w-6 h-6 text-blue-200" />
                </div>
            </div>
            {/* Received Card */}
            <div className="bg-yellow-600 text-white p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <p className="text-yellow-100 text-xs">Received</p>
                        <p className="text-2xl font-bold">{stats.received_complaints}</p> {/* Dynamic Value */}
                    </div>
                    <Clock className="w-6 h-6 text-yellow-200" />
                </div>
            </div>
            {/* Pending Card */}
            <div className="bg-purple-600 text-white p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <p className="text-purple-100 text-xs">Pending</p>
                        <p className="text-2xl font-bold">{stats.pending_complaints}</p> {/* Dynamic Value */}
                    </div>
                    <AlertCircle className="w-6 h-6 text-purple-200" />
                </div>
            </div>
            {/* Resolved Card (Maps to 'closed' in backend) */}
            <div className="bg-green-600 text-white p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <p className="text-green-100 text-xs">Resolved</p>
                        <p className="text-2xl font-bold">{stats.closed_complaints}</p> {/* Dynamic Value */}
                    </div>
                    <CheckCircle className="w-6 h-6 text-green-200" />
                </div>
            </div>
        </div>

{/* Complaints List - 2 Column Layout (Dynamic Data) */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Iterate over the actual fetched data */}
        {displayComplaints.map((complaint) => (
            <div key={complaint.complaint_id} className="bg-white border border-gray-200 p-4 hover:border-blue-300 transition-all">
                <div className="flex items-start justify-between mb-2">
                    <div className="flex-1">
                        {/* Short Description as Title */}
                        <h3 className="text-lg font-semibold text-gray-900 mb-1">{complaint.short_description}</h3>
                        <div className="flex items-center gap-2 mb-2">
                            {/* Dynamic Status */}
                            <span className={`px-2 py-1 text-xs font-medium border text-white 
                                ${complaint.status === 'closed' ? 'bg-green-600 border-green-700' : 
                                complaint.status === 'pending' ? 'bg-purple-600 border-purple-700' : 
                                'bg-yellow-600 border-yellow-700'}`
                            }>
                                {complaint.status.toUpperCase()}
                            </span>
                            
                            {/* Display Category */}
                            {complaint.category && (
                                <span className="px-2 py-1 text-xs font-medium border border-gray-300 bg-gray-100 text-gray-700">
                                    {complaint.category.name}
                                </span>
                            )}
                        </div>
                    </div>
                    {/* Updates/Counter is removed as per request */}
                </div>
                
                {/* Complaint Text as Description */}
                <p className="text-gray-600 text-sm mb-3 line-clamp-3">{complaint.complaint_text}</p>
                
                {/* Resolution Message (Only if closed) */}
                {complaint.status === 'closed' && complaint.resolution_message && (
                    <div className="flex items-start bg-green-50 p-2 my-2 border-l-4 border-green-500">
                        <MessageSquare className="w-4 h-4 text-green-600 flex-shrink-0 mt-1 mr-2" />
                        <p className="text-xs text-gray-700">
                            <span className="font-semibold">Resolution:</span> {complaint.resolution_message}
                        </p>
                    </div>
                )}
                
                <div className="grid grid-cols-1 gap-1 text-xs text-gray-500 mb-3">
                    {/* Submission Date/Time */}
                    <div className="flex items-center">
                        <Calendar className="w-3 h-3 mr-1" />
                        Submitted: {new Date(complaint.timestamp).toLocaleString()}
                    </div>
                    
                    {/* Audio/Video Attachments */}
                    {(complaint.complaint_audio || complaint.complaint_video) && (
                        <div className="flex items-center gap-3 mt-1">
                            {complaint.complaint_audio && (
                                <a href={complaint.complaint_audio} target="_blank" rel="noopener noreferrer" className="flex items-center text-blue-600 hover:underline">
                                    <Volume2 className="w-3 h-3 mr-1" />
                                    Audio Attached
                                </a>
                            )}
                            {complaint.complaint_video && (
                                <a href={complaint.complaint_video} target="_blank" rel="noopener noreferrer" className="flex items-center text-blue-600 hover:underline">
                                    <Video className="w-3 h-3 mr-1" />
                                    Video Attached
                                </a>
                            )}
                        </div>
                    )}

                    {/* Location and AssignedTo are removed */}
                </div>

                <div className="flex justify-between items-center pt-2 border-t border-gray-100">
                    {/* Est. Resolution is removed */}
                    <p className="text-xs text-gray-600">
                        Complaint ID: <span className="font-mono text-gray-900">{complaint.complaint_id.substring(0, 8)}...</span>
                    </p>
                    {/* View/Edit Buttons are removed */}
                    {/* Optional: Add back a View button if you have a detail page */}
                </div>
            </div>
        ))}
    </div>
          </div>
        )}
      </div>

      <Footer />
    </div>
  );
}