import React, { useState, useEffect } from 'react';
import AdminSidebar from '../../components/AdminSidebar';
import AdminNavbar from '../../components/AdminNavbar';
import ResponseModal from '../../components/ResponseModal';
import { Plus, Edit3, Trash2, Eye, Save, X, CheckCircle } from 'lucide-react';

const initialDrafts = [];
const initialPolls = [];
const initialSurveys = [];

const API_BASE_URL = `${import.meta.env.VITE_APP_API_BASE_URL}`;

export default function AdminPollsSurveys() {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [sidebarMinimized, setSidebarMinimized] = useState(false);
  const [tab, setTab] = useState('polls');
  const [showForm, setShowForm] = useState(false);
  const [formType, setFormType] = useState('poll');
  const [drafts, setDrafts] = useState(initialDrafts);
  const [polls, setPolls] = useState(initialPolls);
  const [surveys, setSurveys] = useState(initialSurveys);
  const [editingDraft, setEditingDraft] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [tenants, setTenants] = useState([]);
  const [selectedTenant, setSelectedTenant] = useState(null);
  const [selectedPollSurvey, setSelectedPollSurvey] = useState(null);
  const [formElements, setFormElements] = useState([]);
  const [pollSurveyTitle, setPollSurveyTitle] = useState('');
  const [pollSurveyDescription, setPollSurveyDescription] = useState('');
  const [optionText, setOptionText] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [activePanel, setActivePanel] = useState('drafts');
  const [showStatusModal, setShowStatusModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  const [showResponseModal, setShowResponseModal] = useState(false);
  const [selectedItemResponses, setSelectedItemResponses] = useState(null);
  const [responsesData, setResponsesData] = useState(null);
  const [loadingResponses, setLoadingResponses] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [itemToDelete, setItemToDelete] = useState(null);
  const [deleting, setDeleting] = useState(false);
  const [showDeleteDraftModal, setShowDeleteDraftModal] = useState(false);
  const [draftToDelete, setDraftToDelete] = useState(null);
  const [deletingDraft, setDeletingDraft] = useState(false);
  const [responseTab, setResponseTab] = useState('overview');
  const [newStatus, setNewStatus] = useState('');
  const accessToken = localStorage.getItem('accessToken');
  const userString = localStorage.getItem('user');
  const user = userString ? JSON.parse(userString) : null;
  const isSuperAdmin = user?.is_superuser;

  const [form, setForm] = useState({
    type: 'poll',
    title: '',
    description: '',
    startDate: '',
    endDate: '',
    options: [{ id: 1, text: '' }, { id: 2, text: '' }],
    questions: [{ text: '', question_type: 'multiple_choice', options: ['Option 1', 'Option 2'], ratingMax: 5 }],
    status: 'draft',
    active: false,
  });

  const formatDuration = (startDate, endDate) => {
    const formatDate = (dateString) => {
      if (!dateString) return null;
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    };
  
    const start = formatDate(startDate);
    const end = formatDate(endDate);
  
    if (start && end) {
      return `${start} - ${end}`;
    } else if (start) {
      return `Starting ${start}`;
    } else if (end) {
      return `Ending ${end}`;
    } else {
      return <span className="text-gray-400 italic">No schedule set</span>;
    }
  };
  
  const calculateQuestionStats = (question, responses) => {
  if (!responses || responses.length === 0) return null;

  const questionResponses = responses.map(r => 
    r.answers?.find(a => a.question_id === question.id)
  ).filter(Boolean);

  if (question.question_type === 'multiple_choice' || question.question_type === 'checkbox') {
    const optionCounts = {};
    question.options?.forEach(opt => {
      optionCounts[opt.option_text] = 0;
    });

    questionResponses.forEach(answer => {
      if (Array.isArray(answer.selected_options)) {
        answer.selected_options.forEach(opt => {
          if (optionCounts.hasOwnProperty(opt)) {
            optionCounts[opt]++;
          }
        });
      } else if (answer.selected_option) {
        if (optionCounts.hasOwnProperty(answer.selected_option)) {
          optionCounts[answer.selected_option]++;
        }
      }
    });

    const total = Object.values(optionCounts).reduce((sum, count) => sum + count, 0);
    return { type: 'options', data: optionCounts, total };
  }

  if (question.question_type === 'rating') {
    const ratings = questionResponses
      .map(a => a.rating_value)
      .filter(r => r !== null && r !== undefined);
    
    const average = ratings.length > 0 
      ? (ratings.reduce((sum, r) => sum + r, 0) / ratings.length).toFixed(1)
      : 0;

    const distribution = {};
    for (let i = 1; i <= (question.rating_max || 5); i++) {
      distribution[i] = ratings.filter(r => r === i).length;
    }

    return { type: 'rating', average, distribution, total: ratings.length };
  }

  if (question.question_type === 'text') {
    const textResponses = questionResponses
      .map(a => a.text_response)
      .filter(t => t && t.trim());
    
    return { type: 'text', responses: textResponses, total: textResponses.length };
  }

  return null;
};

  const fetchPollsAndSurveys = async () => {
    if (!accessToken) return;
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/`, {
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      if (!response.ok) throw new Error("Failed to fetch poll/surveys");
      const data = await response.json();

      setPolls(data.filter((item) => item.type === "poll"));
      setSurveys(data.filter((item) => item.type === "survey"));
      console.log("Fetched poll/surveys:", data);
    } catch (err) {
      console.error("Error fetching poll/surveys:", err);
    } finally {
      setLoading(false);
    }
  };

  const fetchResponses = async (item) => {
  setLoadingResponses(true);
  const accessToken = localStorage.getItem("accessToken");
  
  try {
    const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/${item.id}/responses/`, {
      headers: { "Authorization": `Bearer ${accessToken}` },
    });

    if (!response.ok) {
      throw new Error("Failed to fetch responses");
    }

    const data = await response.json();
    setResponsesData(data);
    setSelectedItemResponses(item);
    setShowResponseModal(true);
    setResponseTab('overview');
  } catch (err) {
    console.error(err);
    alert(err.message);
  } finally {
    setLoadingResponses(false);
  }
};

  const handleDeletePollSurvey = async () => {
    if (!itemToDelete) return;

    setDeleting(true);
    const accessToken = localStorage.getItem("accessToken");

    try {
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/${itemToDelete.id}/`, {
        method: "DELETE",
        headers: {
          "Authorization": `Bearer ${accessToken}`,
        },
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to delete");
      }

      if (itemToDelete.type === "poll") {
        setPolls(prev => prev.filter(p => p.id !== itemToDelete.id));
      } else {
        setSurveys(prev => prev.filter(s => s.id !== itemToDelete.id));
      }

      setShowDeleteModal(false);
      setItemToDelete(null);
    } catch (err) {
      console.error(err);
      alert(err.message);
    } finally {
      setDeleting(false);
    }
  };

  useEffect(() => {
    fetchPollsAndSurveys();
  }, []);

  useEffect(() => {
    const fetchDrafts = async () => {
      setLoading(true);
      setError(null);
      const accessToken = localStorage.getItem("accessToken");
      try {
        const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/drafts/`, {
          headers: {
            "Authorization": `Bearer ${accessToken}`,
          },
        });
        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(
            `Failed to fetch drafts: ${response.status} ${response.statusText}. Response: ${errorText}`
          );
        }
        const data = await response.json();
       // console.log("Fetched drafts:", data);
        setDrafts(data);
      } catch (err) {
        setError(err.message);
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchDrafts();
  }, []);

  useEffect(() => {
    const fetchTenants = async () => {
      const accessToken = localStorage.getItem('accessToken');
      const userString = localStorage.getItem('user');
      const user = userString ? JSON.parse(userString) : null;
      const isSuperAdmin = user?.is_superuser;

      if (!isSuperAdmin) return;

      try {
        const res = await fetch(`${API_BASE_URL}/tenants/`, {
          headers: { 'Authorization': `Bearer ${accessToken}` }
        });
        if (!res.ok) throw new Error('Failed to fetch tenants');
        const data = await res.json();
        setTenants(data);
        
        if (data.length > 0) setSelectedTenant(data[0].tenant_id);
        console.log(selectedTenant);
      } catch (err) {
        console.error(err);
        alert(err.message);
      }
    };

    fetchTenants();
  }, []);

  useEffect(() => {
    if (!showForm) {
      setForm({
        type: 'poll',
        title: '',
        description: '',
        startDate: '',
        endDate: '',
        options: [{ id: 1, text: '' }, { id: 2, text: '' }],
        questions: [{ text: '', question_type: 'multiple_choice', options: ['Option 1', 'Option 2'], ratingMax: 5 }],
        status: 'draft',
        active: false,
      });
      setEditingDraft(null);
    }
  }, [showForm]);

  useEffect(() => {
    if (editingDraft) {
      setForm(editingDraft);
      setShowForm(true);
      setFormType(editingDraft.type);
    }
  }, [editingDraft]);

  const handleFormChange = (field, value) => {
    setForm(f => ({ ...f, [field]: value }));
  };

  const handleOptionChange = (idx, value) => {
    setForm(f => ({ ...f, options: f.options.map((o, i) => i === idx ? { ...o, text: value } : o) }));
  };

  const handleQuestionChange = (idx, field, value) => {
    const newQuestions = [...form.questions];
    newQuestions[idx] = { ...newQuestions[idx], [field]: value };
    setForm(f => ({ ...f, questions: newQuestions }));
  };

  const addOptionToQuestion = (qIdx) => {
    const newQuestions = [...form.questions];
    newQuestions[qIdx].options = [...(newQuestions[qIdx].options || []), `Option ${newQuestions[qIdx].options.length + 1}`];
    setForm(f => ({ ...f, questions: newQuestions }));
  };

  const removeOptionFromQuestion = (qIdx, oIdx) => {
    const newQuestions = [...form.questions];
    if (newQuestions[qIdx].options.length > 1) {
      newQuestions[qIdx].options = newQuestions[qIdx].options.filter((_, i) => i !== oIdx);
      setForm(f => ({ ...f, questions: newQuestions }));
    }
  };

  const addQuestion = () => {
    setForm(f => ({
      ...f,
      questions: [...f.questions, { text: '', question_type: 'multiple_choice', options: ['Option 1', 'Option 2'], ratingMax: 5 }]
    }));
  };

  const removeQuestion = (idx) => {
    if (form.questions.length > 1) {
      setForm(f => ({ ...f, questions: f.questions.filter((_, i) => i !== idx) }));
    }
  };

  const normalizeDraft = (draft) => ({
    ...draft,
    updatedAt: draft.updatedAt || draft.updated_at,
    createdAt: draft.createdAt || draft.created_at,
  });

  const handleSaveDraft = async () => {
    if (!form.title) {
      alert("Title is required to save a draft.");
      return;
    }

    const accessToken = localStorage.getItem("accessToken");
    if (!accessToken) {
      alert("Authentication required");
      return;
    }

    const userString = localStorage.getItem("user");
    let user = userString ? JSON.parse(userString) : null;

    const isSuperAdmin = user?.is_superuser;
    const userTenantId = user?.user_roles_set?.[0]?.tenant_id;

    if (!isSuperAdmin && !userTenantId) {
      alert("Only superadmin or officer with tenant can create drafts.");
      return;
    }

    const questionsPayload = form.questions.map((q, idx) => ({
      question_text: q.text || q,
      question_type: q.question_type || "multiple_choice",
      order: idx + 1,
      options: Array.isArray(q.options) ? q.options.map((o) => ({ option_text: o })) : [],
      rating_max: q.question_type === "rating" ? q.ratingMax || 5 : undefined,
    }));

    const payload = {
      title: form.title,
      description: form.description || "",
      start_date: form.startDate || null,
      end_date: form.endDate || null,
      type: form.type,
      status: "draft",
      tenant: isSuperAdmin ? selectedTenant : userTenantId,
      questions: questionsPayload,
    };

    try {
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/`, {
        method: editingDraft ? "PUT" : "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to save draft");
      }

      const data = await response.json();
      const normalized = data.map(normalizeDraft);

      setDrafts((prev) => {
        if (editingDraft) {
          return prev.map((d) => (d.id === editingDraft.id ? data : d));
        }
        return [data, ...prev];
      });

      setShowForm(false);
      setEditingDraft(null);
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

  const handlePublish = async () => {
    const accessToken = localStorage.getItem("accessToken");
    if (!accessToken) {
      alert("Authentication required");
      return;
    }

    const userString = localStorage.getItem("user");
    let user = userString ? JSON.parse(userString) : null;

    const hasPermission = (permission) => user?.user_permissions?.includes(permission);
    const isSuperAdmin = user?.is_superuser;
    const userTenantId = user?.user_roles_set?.[0]?.tenant_id;

    if (!isSuperAdmin && !userTenantId) {
      alert("Only superadmin or officer with tenant can create polls/surveys.");
      return;
    }

    if (!isSuperAdmin && !hasPermission("Create poll/survey.create poll/survey")) {
      alert("You do not have permission to create a poll/survey.");
      return;
    }

    const questionsPayload = form.questions.map((q, idx) => ({
      question_text: q.text || q,
      question_type: q.question_type || "multiple_choice",
      order: idx + 1,
      options: Array.isArray(q.options) ? q.options.map((o) => ({ option_text: o })) : [],
      rating_max: q.question_type === "rating" ? q.ratingMax || 5 : undefined,
    }));

    const payload = {
      title: form.title || "Untitled",
      description: form.description || "",
      start_date: form.startDate || null,
      end_date: form.endDate || null,
      type: form.type,
      status: "active",
      tenant: isSuperAdmin ? selectedTenant : userTenantId,
      questions: questionsPayload,
    };

    try {
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to create poll/survey");
      }

      const data = await response.json();
      form.type === "poll"
        ? setPolls((prev) => [data, ...prev])
        : setSurveys((prev) => [data, ...prev]);
      setShowForm(false);
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

  const handleEditDraft = async (draft) => {
    setLoading(true);
    setError(null);
    const accessToken = localStorage.getItem("accessToken");

    try {
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/${draft.id}/`, {
        headers: { "Authorization": `Bearer ${accessToken}` },
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Failed to fetch draft details: ${response.status} ${response.statusText}. Response: ${errorText}`);
      }

      const detailedDraft = await response.json();
      console.log('Fetched draft details:', detailedDraft);

      setForm({
        title: detailedDraft.title || '',
        description: detailedDraft.description || '',
        startDate: detailedDraft.start_date || '',
        endDate: detailedDraft.end_date || '',
        type: detailedDraft.type || 'poll',
        questions: detailedDraft.questions?.map((q) => {
          // FIX: Use a block body and place console.log before the return statement
          console.log("Options for question:", q.options); 
          
          return {
            text: q.question_text || '',
            question_type: q.question_type || 'multiple_choice',
            options: q.options?.map(o => o.option_text ?? "") || [],
            ratingMax: q.rating_max || 5,
          };
        }) || [],
        tenant: detailedDraft.tenant || null,
        status: detailedDraft.status || 'draft',
      });

      setEditingDraft(detailedDraft);
      setShowForm(true);
      setIsEditing(true);

      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
      console.error(err);
    }
  };

  const handleDeleteDraft = async () => {
    if (!draftToDelete) return;
  
    setDeletingDraft(true);
    const accessToken = localStorage.getItem("accessToken");
  
    try {
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/${draftToDelete.id}/`, {
        method: "DELETE",
        headers: {
          "Authorization": `Bearer ${accessToken}`,
        },
      });
  
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to delete draft");
      }
  
      setDrafts(prev => prev.filter(d => d.id !== draftToDelete.id));
      setShowDeleteDraftModal(false);
      setDraftToDelete(null);
    } catch (err) {
      console.error(err);
      alert(err.message);
    } finally {
      setDeletingDraft(false);
    }
  };

  const handleStatusChange = async () => {
    if (!selectedItem || !newStatus) return;

    const accessToken = localStorage.getItem("accessToken");
    try {
      const response = await fetch(`${API_BASE_URL}/polls_surveys/polls/${selectedItem.id}/`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({ status: newStatus }),
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to update status");
      }

      const updatedItem = await response.json();

      if (selectedItem.type === "poll") {
        setPolls(prev => prev.map(p => p.id === selectedItem.id ? updatedItem : p));
      } else {
        setSurveys(prev => prev.map(s => s.id === selectedItem.id ? updatedItem : s));
      }

      setShowStatusModal(false);
      setSelectedItem(null);
      setNewStatus('');
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

  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 items-center justify-between mb-6">
            <h1 className="text-2xl font-bold text-blue-900">Polls & Surveys Management</h1>
            <button
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              onClick={() => { setShowForm(true); setFormType('poll'); setEditingDraft(null); }}
            >
              <Plus className="w-4 h-4" /> New Poll/Survey
            </button>
          </div>
          <div className="flex gap-2 mb-4">
            <button className={`px-4 py-2 rounded-t ${tab==='polls'?'bg-blue-600 text-white':'bg-white text-blue-900 border'}`} onClick={()=>setTab('polls')}>Polls</button>
            <button className={`px-4 py-2 rounded-t ${tab==='surveys'?'bg-blue-600 text-white':'bg-white text-blue-900 border'}`} onClick={()=>setTab('surveys')}>Surveys</button>
            <button className={`px-4 py-2 rounded-t ${tab==='drafts'?'bg-blue-600 text-white':'bg-white text-blue-900 border'}`} onClick={()=>setTab('drafts')}>Drafts</button>
          </div>
          <div className="bg-white border rounded-b shadow p-6 min-h-[300px]">
            {showForm && (
              <div className="max-w-2xl mx-auto bg-gray-50 border border-blue-200 rounded shadow p-6 mb-8">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-xl font-bold text-blue-900">{editingDraft ? 'Edit Draft' : `New ${formType === 'poll' ? 'Poll' : 'Survey'}`}</h2>
                  <button className="text-gray-500 hover:text-blue-600 text-2xl" onClick={()=>setShowForm(false)}><X /></button>
                </div>
                <div className="flex gap-3 mb-4">
                  <button className={`px-3 py-1 rounded ${formType==='poll'?'bg-blue-600 text-white':'bg-white border text-blue-900'}`} onClick={()=>{setFormType('poll'); handleFormChange('type','poll')}}>Poll</button>
                  <button className={`px-3 py-1 rounded ${formType==='survey'?'bg-blue-600 text-white':'bg-white border text-blue-900'}`} onClick={()=>{setFormType('survey'); handleFormChange('type','survey')}}>Survey</button>
                </div>
                {isSuperAdmin && (
                  <div className="mb-3">
                    <label className="block text-sm font-medium text-gray-700 mb-1">Select Tenant</label>
                    <select
                      className="w-full border px-3 py-2 rounded"
                      value={selectedTenant || ''}
                      onChange={e => setSelectedTenant(e.target.value)}
                    >
                      {tenants.map(t => (
                        <option key={t.tenant_id} value={t.tenant_id}>{t.name}</option>
                      ))}
                    </select>
                  </div>
                )}
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Title</label>
                  <input className="w-full border px-3 py-2 rounded" value={form.title} onChange={e=>handleFormChange('title',e.target.value)} placeholder="Enter title..." />
                </div>
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                  <textarea className="w-full border px-3 py-2 rounded" value={form.description} onChange={e=>handleFormChange('description',e.target.value)} placeholder="Enter description..." />
                </div>
                <div className="mb-3 grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                    <input 
                      type="date" 
                      className="w-full border px-3 py-2 rounded" 
                      value={form.startDate} 
                      onChange={e=>handleFormChange('startDate',e.target.value)} 
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                    <input 
                      type="date" 
                      className="w-full border px-3 py-2 rounded" 
                      value={form.endDate} 
                      onChange={e=>handleFormChange('endDate',e.target.value)} 
                    />
                  </div>
                </div>
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Questions</label>
                  {form.questions.map((q, idx) => (
                    <div key={idx} className="mb-2 border rounded p-2">
                      <input className="w-full border px-3 py-2 rounded mb-1" value={q.text} onChange={e=>handleQuestionChange(idx,'text',e.target.value)} placeholder={`Question ${idx+1}`} />
                      <select className="w-full border px-3 py-2 rounded mb-1" value={q.question_type} onChange={e=>handleQuestionChange(idx,'question_type',e.target.value)}>
                        <option value="multiple_choice">Multiple Choice</option>
                        <option value="checkbox">Checkbox</option>
                        <option value="rating">Rating</option>
                        <option value="text">Text</option>
                      </select>
                      {(q.question_type === 'multiple_choice' || q.question_type === 'checkbox') && (
                        <div className="mb-1">
                          {q.options.map((opt, oIdx) => (
                            <div key={opt.id || oIdx} className="flex gap-2 mb-1">
                              <input 
                                className="flex-1 border px-3 py-1 rounded" 
                                
                                // FIX 1: Access the text property, not the whole object
                                value={opt.option_text || ''} 
                                
                                onChange={e => {
                                  // FIX 2: Create a deep copy of the options array
                                  const newOptions = [...q.options];
                                  
                                  // FIX 3: Update the option_text property of the specific object
                                  newOptions[oIdx] = { 
                                    ...newOptions[oIdx], 
                                    option_text: e.target.value 
                                  };
                                  
                                  // Pass the updated array back to your parent handler
                                  handleQuestionChange(idx, 'options', newOptions);
                                }} 
                              />
                              <button 
                                className="text-red-500" 
                                onClick={() => removeOptionFromQuestion(idx, oIdx)}
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                          ))}
                          <button className="text-blue-600 text-sm mt-1" onClick={() => addOptionToQuestion(idx)}>+ Add Option</button>
                        </div>
                      )}
                      {q.question_type === 'rating' && (
                        <input type="number" className="w-full border px-3 py-1 rounded" value={q.ratingMax} onChange={e => handleQuestionChange(idx,'ratingMax',Number(e.target.value))} placeholder="Max rating" />
                      )}
                      {form.questions.length > 1 && <button className="text-red-500 mt-1" onClick={()=>removeQuestion(idx)}><Trash2 className="w-4 h-4" /> Remove Question</button>}
                    </div>
                  ))}
                  <button className="text-blue-600 text-sm mt-1" onClick={addQuestion}>+ Add Question</button>
                </div>
                <div className="flex gap-2 mt-6">
                  <button className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 flex items-center gap-2" onClick={handleSaveDraft}><Save className="w-4 h-4" />Save as Draft</button>
                  <button className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-2" onClick={handlePublish}><CheckCircle className="w-4 h-4" />Publish</button>
                </div>
              </div>
            )}
            {tab==='drafts' && (
              <div>
                <h2 className="text-lg font-bold text-blue-900 mb-4">Drafts</h2>
                {drafts.length === 0 ? (
                  <div className="text-gray-400 text-center py-8">No drafts yet.</div>
                ) : (
                  <div className="space-y-3">
                    {drafts.map(draft => (
                      <div key={draft.id} className="flex items-center justify-between bg-gray-50 border rounded p-3">
                        <div>
                          <div className="font-semibold text-blue-900">{draft.title || <span className='italic text-gray-400'>Untitled</span>}</div>
                          <div className="text-xs text-gray-500">{draft.type === 'poll' ? 'Poll' : 'Survey'} &middot; Last edited {new Date(draft.updated_at || draft.updatedAt).toLocaleString()}</div>
                        </div>
                        <div className="flex gap-2">
                          <button className="text-blue-600 hover:underline" onClick={() => {setShowForm(true); handleEditDraft(draft)}}><Edit3 className="w-4 h-4 inline" /> Edit</button>
                          <button className="text-red-500 hover:underline" onClick={() => {setDraftToDelete(draft); setShowDeleteDraftModal(true);}}><Trash2 className="w-4 h-4 inline" /> Delete</button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
            {tab==='polls' && (
              <div>
                <h2 className="text-lg font-bold text-blue-900 mb-4">Polls</h2>
                {polls.length === 0 ? (
                  <div className="text-gray-400 text-center py-8">No polls yet.</div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="min-w-full border">
                      <thead className="bg-blue-600">
                        <tr>
                          <th className="text-white px-3 py-2 text-left">Title</th>
                          <th className="text-white px-3 py-2 text-left">Status</th>
                          <th className="text-white px-3 py-2 text-left">Duration</th>
                          <th className="text-white px-3 py-2 text-left">Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                        {polls.map(poll => (
                          <tr key={poll.id} className="border-b">
                            <td className="px-3 py-2">{poll.title}</td>
                            <td className="px-3 py-2">
                              <span className={`px-2 py-1 rounded text-xs font-medium ${
                                poll.status === 'active' ? 'bg-green-100 text-green-800' :
                                poll.status === 'draft' ? 'bg-gray-100 text-gray-800' :
                                poll.status === 'closed' ? 'bg-red-100 text-red-800' :
                                'bg-blue-100 text-blue-800'
                              }`}>
                                {poll.status}
                              </span>
                            </td>
                            <td className="px-3 py-2 text-sm">{formatDuration(poll.start_date, poll.end_date)}</td>
                            <td className="px-3 py-2 flex gap-5">
                              <button className="text-blue-600 hover:underline" onClick={() => fetchResponses(poll)}> <Eye className="w-4 h-4 inline" /> View</button>
                              <button 
                                className="text-green-600 hover:underline"
                                onClick={() => {
                                  setSelectedItem(poll);
                                  setNewStatus(poll.status);
                                  setShowStatusModal(true);
                                }}
                              >
                                Change Status
                              </button>
                              <button className="text-red-600 hover:underline" onClick={() => {setItemToDelete(poll); setShowDeleteModal(true);}}><Trash2 className="w-4 h-4 inline" /> Delete</button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}
            {tab==='surveys' && (
              <div>
                <h2 className="text-lg font-bold text-blue-900 mb-4">Surveys</h2>
                {surveys.length === 0 ? (
                  <div className="text-gray-400 text-center py-8">No surveys yet.</div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="min-w-full border">
                      <thead className="bg-blue-600">
                        <tr>
                          <th className="text-white px-3 py-2 text-left">Title</th>
                          <th className="text-white px-3 py-2 text-left">Status</th>
                          <th className="text-white px-3 py-2 text-left">Duration</th>
                          <th className="text-white px-3 py-2 text-left">Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                      {surveys.map(survey => (
                        <tr key={survey.id} className="border-b">
                          <td className="px-3 py-2">{survey.title}</td>
                          <td className="px-3 py-2">
                            <span className={`px-2 py-1 rounded text-xs font-medium ${
                              survey.status === 'active' ? 'bg-green-100 text-green-800' :
                              survey.status === 'draft' ? 'bg-gray-100 text-gray-800' :
                              survey.status === 'closed' ? 'bg-red-100 text-red-800' :
                              'bg-blue-100 text-blue-800'
                            }`}>
                              {survey.status}
                            </span>
                          </td>
                          <td className="px-3 py-2 text-sm">{formatDuration(survey.start_date, survey.end_date)}</td>
                          <td className="px-3 py-2 flex gap-5">
                          <button className="text-blue-600 hover:underline"onClick={() => fetchResponses(survey)}> <Eye className="w-4 h-4 inline" /> View</button>
                            <button 
                              className="text-green-600 hover:underline"
                              onClick={() => {
                                setSelectedItem(survey);
                                setNewStatus(survey.status);
                                setShowStatusModal(true);
                              }}
                            >
                              Change Status
                            </button>
                            <button className="text-red-600 hover:underline" onClick={() => { setItemToDelete(survey); setShowDeleteModal(true);}}><Trash2 className="w-4 h-4 inline" /> Delete</button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}
          </div>
        </main>
      </div>

      {showStatusModal && (
        <div className="fixed inset-0 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl p-6 w-96">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-blue-900">Change Status</h3>
              <button 
                className="text-gray-500 hover:text-blue-600"
                onClick={() => {
                  setShowStatusModal(false);
                  setSelectedItem(null);
                  setNewStatus('');
                }}
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Current Status: <span className="font-semibold">{selectedItem?.status}</span>
              </label>
              <label className="block text-sm font-medium text-gray-700 mb-1">Select New Status</label>
              <select
                className="w-full border px-3 py-2 rounded"
                value={newStatus}
                onChange={(e) => setNewStatus(e.target.value)}
              >
                <option value="draft">Draft</option>
                <option value="active">Active</option>
                <option value="closed">Closed</option>
                <option value="archived">Archived</option>
              </select>
            </div>
            <div className="flex gap-2 justify-end">
              <button
                className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                onClick={() => {
                  setShowStatusModal(false);
                  setSelectedItem(null);
                  setNewStatus('');
                }}
              >
                Cancel
              </button>
              <button
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                onClick={handleStatusChange}
              >
                Update Status
              </button>
            </div>
          </div>
        </div>
      )}  
      {showDeleteModal && itemToDelete && (
  <div className="fixed inset-0 backdrop-blur-sm bg-opacity-50 flex items-center justify-center z-50">
    <div className="bg-white rounded-lg shadow-xl p-6 w-96">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-bold text-blue-900">Confirm Delete</h3>
        <button 
          className="text-gray-500 hover:text-blue-600"
          onClick={() => {
            setShowDeleteModal(false);
            setItemToDelete(null);
          }}
          disabled={deleting}
        >
          <X className="w-5 h-5" />
        </button>
      </div>
      <div className="mb-6">
        <p className="text-gray-700 mb-2">
          Are you sure you want to delete this {itemToDelete.type === 'poll' ? 'poll' : 'survey'}?
        </p>
        <div className="bg-red-50 border border-red-200 rounded p-3">
          <p className="font-semibold text-red-900">{itemToDelete.title}</p>
          <p className="text-sm text-red-700 mt-1">
            This action cannot be undone. All responses will be permanently deleted.
          </p>
        </div>
      </div>
      <div className="flex gap-2 justify-end">
        <button
          className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
          onClick={() => {
            setShowDeleteModal(false);
            setItemToDelete(null);
          }}
          disabled={deleting}
        >
          Cancel
        </button>
        <button
          className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 flex items-center gap-2 disabled:bg-red-400"
          onClick={handleDeletePollSurvey}
          disabled={deleting}
        >
          <Trash2 className="w-4 h-4" />
          {deleting ? 'Deleting...' : 'Delete'}
        </button>
      </div>
    </div>
  </div>
)}    
      <ResponseModal
        // State for visibility and data
        showResponseModal={showResponseModal}
        selectedItemResponses={selectedItemResponses}
        responsesData={responsesData}
        loadingResponses={loadingResponses}
        responseTab={responseTab}
        
        // State Setters (Functions to change the state)
        setShowResponseModal={setShowResponseModal}
        setSelectedItemResponses={setSelectedItemResponses}
        setResponsesData={setResponsesData}
        setResponseTab={setResponseTab}

        // Helper functions
        formatDuration={formatDuration}
        calculateQuestionStats={calculateQuestionStats}
      />
      {showDeleteDraftModal && draftToDelete && (
  <div className="fixed inset-0 backdrop-blur-sm bg-opacity-50 flex items-center justify-center z-50">
    <div className="bg-white rounded-lg shadow-xl p-6 w-96">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-bold text-blue-900">Confirm Delete Draft</h3>
        <button 
          className="text-gray-500 hover:text-blue-600"
          onClick={() => {
            setShowDeleteDraftModal(false);
            setDraftToDelete(null);
          }}
          disabled={deletingDraft}
        >
          <X className="w-5 h-5" />
        </button>
      </div>
      <div className="mb-6">
        <p className="text-gray-700 mb-2">
          Are you sure you want to delete this draft?
        </p>
        <div className="bg-red-50 border border-red-200 rounded p-3">
          <p className="font-semibold text-red-900">
            {draftToDelete.title || <span className="italic text-gray-400">Untitled</span>}
          </p>
          <p className="text-sm text-red-700 mt-1">
            This action cannot be undone.
          </p>
        </div>
      </div>
      <div className="flex gap-2 justify-end">
        <button
          className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
          onClick={() => {
            setShowDeleteDraftModal(false);
            setDraftToDelete(null);
          }}
          disabled={deletingDraft}
        >
          Cancel
        </button>
        <button
          className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 flex items-center gap-2 disabled:bg-red-400"
          onClick={handleDeleteDraft}
          disabled={deletingDraft}
        >
          <Trash2 className="w-4 h-4" />
          {deletingDraft ? 'Deleting...' : 'Delete'}
        </button>
      </div>
    </div>
  </div>
)}
    </div>
  );
}