import React, { useState, useEffect, useCallback } from 'react';
import AdminNavbar from '../../components/AdminNavbar';
import AdminSidebar from '../../components/AdminSidebar';
import { Eye, Edit3, Filter, Search, Video , Loader2 } from 'lucide-react';
import axios from 'axios';

const API_BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;

const getStatusClasses = (status) => {
  switch (status) {
      case 'received':
          return 'bg-yellow-100 text-yellow-800';
      case 'pending':
          return 'bg-blue-100 text-blue-800';
      case 'closed':
          return 'bg-green-100 text-green-800';
      default:
          return 'bg-gray-100 text-gray-700';
  }
};

const EditComplaintModal = ({ complaint, onClose, onUpdateSuccess, API_BASE_URL }) => {
  const [status, setStatus] = useState(complaint.status);
  const [resolutionMessage, setResolutionMessage] = useState(complaint.resolution_message || '');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);
  
  // Status options that the admin can select
  const statusOptions = ['received', 'pending', 'closed'];

  const handleUpdate = async (e) => {
      e.preventDefault();
      setError(null);
      setIsSubmitting(true);

      const accessToken = localStorage.getItem("accessToken");
      if (!accessToken) {
          setError("Admin not authenticated.");
          setIsSubmitting(false);
          return;
      }

      const payload = {
          status: status,
      };

      // Only include resolution message if status is closed, otherwise it's null/empty
      if (status === 'closed') {
          if (!resolutionMessage.trim()) {
              // Frontend validation based on backend requirement
              setError("A resolution message is required to close the complaint.");
              setIsSubmitting(false);
              return;
          }
          payload.resolution_message = resolutionMessage;
      } else {
           // Ensure resolution_message is cleared if status changes from closed
          payload.resolution_message = ""; 
      }

      try {
          const url = `${API_BASE_URL}/complaints/ministry/complaints/${complaint.complaint_id}/`;
          
          // Use PATCH method as defined in your Django ViewSet
          await axios.patch(url, payload, {
              headers: {
                  'Authorization': `Bearer ${accessToken}`,
                  'Content-Type': 'application/json'
              }
          });

          // Call the success handler to refresh the list in the parent component
          onUpdateSuccess();
          onClose();

      } catch (err) {
          console.error("Error updating complaint status:", err.response || err);
          
          // Handle validation errors from the backend serializer
          let errorMessage = "Failed to update complaint status.";
          if (err.response && err.response.data) {
              if (err.response.data.resolution_message) {
                   errorMessage = `Error: ${err.response.data.resolution_message}`;
              } else if (err.response.data.detail) {
                  errorMessage = err.response.data.detail;
              }
          }
          setError(errorMessage);
      } finally {
          setIsSubmitting(false);
      }
  };

  return (
      <div className="fixed inset-0 z-50  flex items-start justify-center p-4 sm:p-8 pointer-events-none">
          <div className="relative mt-12 w-full max-w-lg bg-white rounded-xl shadow-2xl transform transition-all duration-300 pointer-events-auto">
              
              <div className="flex items-center justify-between bg-blue-600 px-6 py-4 rounded-t-xl">
                  <h2 className="text-xl font-bold text-white tracking-wide">Edit Complaint Status</h2>
                  <button onClick={onClose} className="text-white hover:text-yellow-200 text-2xl font-bold ml-4">&times;</button>
              </div>

              <form onSubmit={handleUpdate} className="p-6 space-y-5">
                  
                  
                  <div className="bg-gray-50 p-4 rounded-lg border border-gray-200">
                      <h3 className="text-lg font-semibold mb-3 text-gray-800 border-b pb-2">Complaint Info</h3>
                      <div className="space-y-3 text-sm text-gray-700">
                          {/* 1. Category Name */}
                          <div><span className="font-semibold text-gray-900">Category Name:</span> {complaint.category_name}</div>
                          
                          {/* 2. Short Description */}
                          <div><span className="font-semibold text-gray-900">Short Description:</span> {complaint.short_description}</div>
                          
                          {/* 3. Submitted */}
                          <div><span className="font-semibold text-gray-900">Submitted:</span> {new Date(complaint.timestamp).toLocaleDateString()}</div>

                          {/* 4. Complaint Text (Full width) */}
                          <div className="pt-2 border-t mt-3"><span className="font-semibold text-gray-900">Full Text:</span> {complaint.complaint_text}</div>
                          
                           {/* 5. Media Links */}
                          <div className="flex gap-4 pt-2">
                              <span className="font-semibold text-gray-900">Media:</span>
                              {complaint.complaint_audio ? (
                                  <a href={complaint.complaint_audio} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline flex items-center gap-1"><Volume2 className="w-4 h-4" />Audio</a>
                              ) : (
                                  <span className="text-gray-400">Audio (-)</span>
                              )}
                              {complaint.complaint_video ? (
                                  <a href={complaint.complaint_video} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline flex items-center gap-1"><Video className="w-4 h-4" />Video</a>
                              ) : (
                                  <span className="text-gray-400">Video (-)</span>
                              )}
                          </div>
                      </div>
                  </div>
                  
                  {/* Status Update Form */}
                  <div className="space-y-4">
                      <label htmlFor="status" className="block text-sm font-medium text-gray-700">Update Status:</label>
                      <select
                          id="status"
                          value={status}
                          onChange={(e) => {
                              setStatus(e.target.value);
                              // Clear error when status changes
                              setError(null); 
                          }}
                          className="w-full p-2 border border-gray-300 rounded-lg shadow-sm focus:ring-yellow-500 focus:border-yellow-500 text-base"
                          disabled={isSubmitting}
                      >
                          {statusOptions.map(opt => (
                              <option key={opt} value={opt}>
                                  {opt.toUpperCase()}
                              </option>
                          ))}
                      </select>
                  </div>

                  {/* Resolution Message Input (Conditional) */}
                  {status === 'closed' && (
                      <div className="space-y-2">
                          <label htmlFor="resolution_message" className="block text-sm font-medium text-gray-700">
                              Resolution Message (Required for Closure):
                          </label>
                          <textarea
                              id="resolution_message"
                              value={resolutionMessage}
                              onChange={(e) => setResolutionMessage(e.target.value)}
                              rows="3"
                              className="w-full p-2 border border-gray-300 rounded-lg shadow-sm focus:ring-yellow-500 focus:border-yellow-500 text-sm"
                              placeholder="Enter the final resolution details..."
                              disabled={isSubmitting}
                              required
                          />
                      </div>
                  )}

                  {/* Error Message */}
                  {error && (
                      <div className="p-3 bg-red-100 border border-red-400 text-red-700 rounded-lg text-sm" role="alert">
                          {error}
                      </div>
                  )}

                  {/* Submit Button */}
                  <div className="pt-4 border-t border-gray-200">
                      <button
                          type="submit"
                          className="w-full flex items-center justify-center px-4 py-2 border border-transparent text-base font-medium rounded-lg shadow-sm text-white bg-blue-600 hover:bg-yellow-700 transition-colors disabled:opacity-50"
                          disabled={isSubmitting}
                      >
                          {isSubmitting ? (
                              <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                          ) : (
                              'Save Status Update'
                          )}
                      </button>
                  </div>
              </form>
          </div>
      </div>
  );
};

function ComplaintDetailsModal({ complaint, onClose }) {
  if (!complaint) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pointer-events-none">
    <div className="relative mt-24 w-full max-w-lg pointer-events-auto">
        <div className="bg-white border border-blue-600 w-full shadow-2xl" style={{ borderRadius: 8 }}>
            <div className="flex items-center justify-between bg-blue-600 px-6 py-4" style={{ borderTopLeftRadius: 8, borderTopRightRadius: 8 }}>
                <h2 className="text-xl font-bold text-white tracking-wide">Complaint Details</h2>
                <button onClick={onClose} className="text-white hover:text-blue-200 text-2xl font-bold ml-4">&times;</button>
            </div>
            <div className="p-6 space-y-4">
                <div className="grid grid-cols-1 gap-y-4">
                    <div><span className="font-semibold text-gray-700">Category Name:</span> {complaint.category_name}</div>
                    <div><span className="font-semibold text-gray-700">Short Description:</span> {complaint.short_description}</div>
                    <div><span className="font-semibold text-gray-700">Complaint Text:</span> {complaint.complaint_text}</div>
                    <div><span className="font-semibold text-gray-700">Status:</span> {complaint.status}</div>
                    <div><span className="font-semibold text-gray-700">Submitted:</span> {new Date(complaint.timestamp).toLocaleDateString()}</div>
                    <div>
                        <span className="font-semibold text-gray-700">Complaint Audio:</span> 
                        {complaint.complaint_audio ? (
                            <a href={complaint.complaint_audio} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline ml-2">View Audio</a>
                        ) : (
                            <span className="text-gray-400 ml-2">-</span>
                        )}
                    </div>
                    <div>
                        <span className="font-semibold text-gray-700">Complaint Video:</span> 
                        {complaint.complaint_video ? (
                            <a href={complaint.complaint_video} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline ml-2">View Video</a>
                        ) : (
                            <span className="text-gray-400 ml-2">-</span>
                        )}
                    </div>
                    {complaint.status === 'closed' && complaint.resolution_message && (
                        <div className="mt-4 p-3 bg-green-50 border-l-4 border-green-600">
                            <span className="font-bold text-green-800">Resolution:</span> {complaint.resolution_message}
                        </div>
                    )}
                </div>
            </div>
        </div>
    </div>
</div>
  );
}

export default function AdminComplaints() {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [sidebarMinimized, setSidebarMinimized] = useState(false);
  
  // Complaints List State
  const [complaints, setComplaints] = useState([]); // Stores the fetched list
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [totalComplaints, setTotalComplaints] = useState(0); // To store total count for pagination

  // Filtering & Pagination State
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [page, setPage] = useState(1);
  const rowsPerPage = 10;

  const [viewComplaint, setViewComplaint] = useState(null);
  const [editingComplaint, setEditingComplaint] = useState(null);

  const fetchComplaints = useCallback(async () => {
    const accessToken = localStorage.getItem("accessToken");
    if (!accessToken) {
        setError("Admin not authenticated.");
        setIsLoading(false);
        return;
    }

    setIsLoading(true);
    setError(null);
    
    const offset = (page - 1) * rowsPerPage;
    let url = `${API_BASE_URL}/complaints/ministry/complaints/?limit=${rowsPerPage}&offset=${offset}`;

    if (statusFilter !== 'all') {
        url += `&status=${statusFilter}`;
    }
    
    if (searchTerm) {
        url += `&search=${searchTerm}`; 
    }

    try {
        const response = await axios.get(url, {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });
        
        // --- CRITICAL DEBUGGING STEP ---
        console.log("API Response Data Structure:", response.data);
        // -------------------------------
        
        let fetchedComplaints = [];
        let totalCount = 0;

        // Check if the response is a standard DRF paginated object
        if (response.data && Array.isArray(response.data.results)) {
            fetchedComplaints = response.data.results;
            totalCount = response.data.count || fetchedComplaints.length;
            console.log("Data handled as PAGINATED response.");
        } 
        // If not paginated, assume the entire response.data is the array
        else if (Array.isArray(response.data)) {
            fetchedComplaints = response.data;
            totalCount = fetchedComplaints.length; // Set total count to length of data
            console.log("Data handled as NON-PAGINATED array.");
        } else {
            // Handle unexpected structure
            console.error("API Response structure is unexpected:", response.data);
            setError("Received unexpected data format from the server.");
        }
        
        setComplaints(fetchedComplaints);
        setTotalComplaints(totalCount);
        
    } catch (err) {
        console.error("Error fetching admin complaints:", err.response || err);
        setError(err.response?.data?.detail || "Failed to load complaints from API.");
        setComplaints([]);
    } finally {
        setIsLoading(false);
    }
}, [page, rowsPerPage, statusFilter, searchTerm]); // Dependencies for re-fetching


    
   
    useEffect(() => {
        fetchComplaints();
    }, [fetchComplaints]);
    
   
    useEffect(() => { 
        setPage(1); 
    }, [searchTerm, statusFilter]);
    
   
    const totalPages = Math.ceil(totalComplaints / rowsPerPage) || 1;
    
    const handlePageChange = (newPage) => {
        if (newPage >= 1 && newPage <= totalPages) setPage(newPage);
    };

    const handleUpdateSuccess = useCallback(() => {
      fetchComplaints();
  }, [fetchComplaints]); 




  return (
    <div className="flex h-screen bg-gray-50">
      <AdminSidebar
        open={sidebarOpen}
        minimized={sidebarMinimized}
        onClose={() => setSidebarOpen(false)}
        onMinimize={() => setSidebarMinimized(!sidebarMinimized)}
        onOpen={() => setSidebarOpen(true)}
      />
      <div className="flex-1 flex flex-col overflow-hidden">
        <AdminNavbar
          onMenuToggle={() => setSidebarOpen(!sidebarOpen)}
          sidebarOpen={sidebarOpen}
        />
        <main className="flex-1 overflow-y-auto p-6">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 font-poppins">All Complaints</h1>
              <p className="text-gray-600 font-inter mt-1">View, filter, and manage all citizen complaints</p>
            </div>
          </div>
          {/* Search and Filter Bar */}
          <div className="bg-white border border-gray-200 p-4 mb-6 rounded-lg flex flex-col md:flex-row gap-3 items-center">
            <div className="flex-1 relative w-full">
              <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 rounded-md"
              />
            </div>
            <div className="flex gap-3 w-full md:w-auto">
              <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 rounded-md"
              >
                <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 rounded-md">
                <Filter className="w-4 h-4 mr-1" />
                Filter
              </button>
            </div>
          </div>
          {/* Complaints Table */}
<div className="overflow-x-auto bg-white rounded-lg shadow border border-gray-200">
    <table className="min-w-full divide-y divide-gray-200">
        <thead className="bg-blue-600">
            <tr>
                {/* <th>ID</th> REMOVED */}
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Title (Short Desc)</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Category</th>
                {/* <th>Citizen</th> REMOVED */}
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Status</th>
                {/* <th>Priority</th> REMOVED */}
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Submitted</th>
                {/* <th>Assigned To</th> REMOVED */}
                
                {/* NEW COLUMNS */}
                <th className="px-4 py-3 text-center text-xs font-medium text-white uppercase tracking-wider">Audio</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-white uppercase tracking-wider">Video</th>
                
                <th className="px-4 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Actions</th>
            </tr>
        </thead>
        <tbody className="bg-white divide-y divide-gray-100">
            {isLoading ? (
                <tr>
                    <td colSpan="7" className="px-4 py-4 text-center text-gray-500">Loading complaints...</td>
                </tr>
            ) : error ? (
                 <tr>
                    <td colSpan="7" className="px-4 py-4 text-center text-red-600">{error}</td>
                </tr>
            ) : complaints.length === 0 ? (
                <tr>
                    <td colSpan="7" className="px-4 py-4 text-center text-gray-500">No complaints found.</td>
                </tr>
            ) : (
                complaints.map((complaint, idx) => (
                    <tr key={complaint.complaint_id} className={`${idx % 2 === 1 ? 'bg-gray-100' : ''} hover:bg-blue-50 transition-colors`}>
                        {/* Title (Short Description) */}
                        <td className="px-4 py-2 text-sm text-gray-900 font-medium whitespace-nowrap">
                            {complaint.short_description}
                        </td>
                        
                        {/* Category Name */}
                        <td className="px-4 py-2 text-sm text-gray-700 whitespace-nowrap">
                            {complaint.category_name || '-'}
                        </td>
                        
                        {/* Status */}
                        <td className="px-4 py-2 text-sm whitespace-nowrap">
                            <span className={`px-2 py-1 rounded-full text-xs font-semibold ${
                                // Use your three status choices: received, pending, closed
                                complaint.status === 'received' ? 'bg-yellow-100 text-yellow-800' :
                                complaint.status === 'pending' ? 'bg-blue-100 text-blue-800' :
                                complaint.status === 'closed' ? 'bg-green-100 text-green-800' :
                                'bg-gray-100 text-gray-700'
                            }`}>
                                {complaint.status.toUpperCase()}
                            </span>
                        </td>
                        
                        {/* Submitted Date */}
                        <td className="px-4 py-2 text-sm text-gray-700 whitespace-nowrap">
                            {new Date(complaint.timestamp).toLocaleDateString()}
                        </td>

                        {/* Audio */}
                        <td className="px-4 py-2 text-sm text-center">
                            {complaint.complaint_audio ? (
                                <a href={complaint.complaint_audio} target="_blank" rel="noopener noreferrer" title="View Audio">
                                    <Volume2 className="w-4 h-4 text-blue-600 mx-auto hover:text-blue-800" />
                                </a>
                            ) : (
                                <span className="text-gray-400">-</span>
                            )}
                        </td>
                        
                        {/* Video */}
                        <td className="px-4 py-2 text-sm text-center">
                            {complaint.complaint_video ? (
                                <a href={complaint.complaint_video} target="_blank" rel="noopener noreferrer" title="View Video">
                                    <Video className="w-4 h-4 text-blue-600 mx-auto hover:text-blue-800" />
                                </a>
                            ) : (
                                <span className="text-gray-400">-</span>
                            )}
                        </td>
                        
                        {/* Actions */}
                        <td className="px-4 py-2 text-sm flex gap-5 whitespace-nowrap">
                            <button className="p-1 text-blue-600 hover:bg-blue-50 transition-all" title="View" onClick={() => setViewComplaint(complaint)}>
                                <Eye className="w-4 h-4" />
                            </button>
                            {/* The Edit button will be crucial for updating status/resolution */}
                            <button 
                                            className="p-1 text-yellow-600 hover:bg-yellow-50 transition-all rounded-md" 
                                            title="Edit Status/Resolve"
                                            onClick={() => setEditingComplaint(complaint)} 
                                        >
                                            <Edit3 className="w-4 h-4" />
                                        </button>
                        </td>
                    </tr>
                ))
            )}
        </tbody>
    </table>
</div>

{/* Pagination Controls must be updated to use totalComplaints from API */}
<div className="flex justify-between items-center py-4">
    <span className="text-sm text-gray-600">
        Showing {totalComplaints === 0 ? 0 : (page - 1) * rowsPerPage + 1}
        -{Math.min(page * rowsPerPage, totalComplaints)} of {totalComplaints} complaints
    </span>
    <div className="flex gap-2">
        <button
            className="px-3 py-1 rounded bg-gray-200 text-gray-700 hover:bg-blue-100 disabled:opacity-50"
            onClick={() => handlePageChange(page - 1)}
            disabled={page === 1}
        >
            Previous
        </button>
        <span className="px-2 py-1 text-gray-700">Page {page} of {totalPages}</span>
        <button
            className="px-3 py-1 rounded bg-gray-200 text-gray-700 hover:bg-blue-100 disabled:opacity-50"
            onClick={() => handlePageChange(page + 1)}
            disabled={page === totalPages}
        >
            Next
        </button>
    </div>
</div>


          {/* Modals */}
          {viewComplaint && (
                <ComplaintDetailsModal complaint={viewComplaint} onClose={() => setViewComplaint(null)} />
            )}

            {/* 🛠️ NEW EDIT MODAL RENDER 🛠️ */}
            {editingComplaint && (
                <EditComplaintModal 
                    complaint={editingComplaint} 
                    onClose={() => setEditingComplaint(null)} 
                    onUpdateSuccess={handleUpdateSuccess} 
                    API_BASE_URL={API_BASE_URL}
                />
            )}
        </main>
      </div>
    </div>
  );
}
