import React, { useState, useEffect } from 'react';
import { ChevronRight, Clock, Users, TrendingUp, Vote, CheckCircle, XCircle, BarChart3, PieChart, Calendar, Filter, Search, Eye, MessageSquare } from 'lucide-react';
import Footer from '../components/Footer';

const PollsSurveys = () => {
  const [activeTab, setActiveTab] = useState('active');
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCategory, setFilterCategory] = useState('all');
  const [sortBy, setSortBy] = useState('recent');

  // Sample data - in real app, fetch from API
  const [polls, setPolls] = useState([
    {
      id: 1,
      title: "Government Budget Allocation Priorities for 2025",
      description: "Help us understand which sectors should receive increased funding in the upcoming fiscal year.",
      type: "poll",
      category: "budget",
      status: "active",
      endDate: "2025-10-15",
      totalVotes: 1247,
      totalResponses: 1247,
      myVote: null,
      options: [
        { id: 1, text: "Healthcare and Medical Services", votes: 456, percentage: 36.6 },
        { id: 2, text: "Education and Schools", votes: 378, percentage: 30.3 },
        { id: 3, text: "Infrastructure and Roads", votes: 289, percentage: 23.2 },
        { id: 4, text: "Agriculture and Rural Development", votes: 124, percentage: 9.9 }
      ],
      createdAt: "2025-09-15"
    },
    {
      id: 2,
      title: "Public Transportation Service Quality Assessment",
      description: "Share your experience with public transportation services in your area to help us improve.",
      type: "survey",
      category: "transport",
      status: "active",
      endDate: "2025-11-01",
      totalVotes: 0,
      totalResponses: 892,
      myVote: null,
      questions: [
        "How often do you use public transportation?",
        "Rate the cleanliness of public transport vehicles",
        "How would you rate the punctuality of services?",
        "What improvements would you suggest?"
      ],
      createdAt: "2025-09-20"
    },
    {
      id: 3,
      title: "Digital Government Services Satisfaction",
      description: "Rate your experience with online government services and digital platforms.",
      type: "survey",
      category: "digital",
      status: "completed",
      endDate: "2025-09-30",
      totalVotes: 0,
      totalResponses: 2156,
      myVote: null,
      questions: [
        "How easy is it to access government services online?",
        "Rate the user-friendliness of government websites",
        "How reliable are digital government platforms?"
      ],
      createdAt: "2025-08-15"
    },
    {
      id: 4,
      title: "Preferred Communication Channels for Government Updates",
      description: "Tell us how you'd like to receive important government announcements and updates.",
      type: "poll",
      category: "communication",
      status: "active",
      endDate: "2025-10-30",
      totalVotes: 743,
      totalResponses: 743,
      myVote: 2,
      options: [
        { id: 1, text: "SMS Text Messages", votes: 198, percentage: 26.6 },
        { id: 2, text: "Email Newsletters", votes: 267, percentage: 35.9 },
        { id: 3, text: "Social Media Posts", votes: 156, percentage: 21.0 },
        { id: 4, text: "Mobile App Notifications", votes: 122, percentage: 16.4 }
      ],
      createdAt: "2025-09-10"
    }
  ]);

  const categories = [
    { value: 'all', label: 'All Categories' },
    { value: 'budget', label: 'Budget & Finance' },
    { value: 'transport', label: 'Transportation' },
    { value: 'digital', label: 'Digital Services' },
    { value: 'communication', label: 'Communication' },
    { value: 'health', label: 'Healthcare' },
    { value: 'education', label: 'Education' }
  ];

  const handleVote = (pollId, optionId) => {
    setPolls(prev => prev.map(poll => {
      if (poll.id === pollId && poll.type === 'poll') {
        const updatedOptions = poll.options.map(option => {
          if (option.id === optionId) {
            return { ...option, votes: option.votes + 1 };
          }
          return option;
        });
        const newTotal = poll.totalVotes + 1;
        const recalculatedOptions = updatedOptions.map(option => ({
          ...option,
          percentage: Number(((option.votes / newTotal) * 100).toFixed(1))
        }));
        
        return {
          ...poll,
          options: recalculatedOptions,
          totalVotes: newTotal,
          myVote: optionId
        };
      }
      return poll;
    }));
  };

  const filteredPolls = polls.filter(poll => {
    const matchesSearch = poll.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         poll.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = filterCategory === 'all' || poll.category === filterCategory;
    const matchesTab = activeTab === 'all' || poll.status === activeTab;
    
    return matchesSearch && matchesCategory && matchesTab;
  });

  const sortedPolls = [...filteredPolls].sort((a, b) => {
    switch (sortBy) {
      case 'recent':
        return new Date(b.createdAt) - new Date(a.createdAt);
      case 'popular':
        return (b.totalVotes + b.totalResponses) - (a.totalVotes + a.totalResponses);
      case 'ending':
        return new Date(a.endDate) - new Date(b.endDate);
      default:
        return 0;
    }
  });

  const getStatusColor = (status) => {
    switch (status) {
      case 'active': return 'text-green-600 bg-green-50 border-green-200';
      case 'completed': return 'text-blue-600 bg-blue-50 border-blue-200';
      case 'draft': return 'text-gray-600 bg-gray-50 border-gray-200';
      default: return 'text-gray-600 bg-gray-50 border-gray-200';
    }
  };

  const getDaysRemaining = (endDate) => {
    const today = new Date();
    const end = new Date(endDate);
    const diffTime = end - today;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header Section */}
      <div className="bg-white border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="text-center">
            <h1 className="text-3xl md:text-4xl font-bold text-blue-900 mb-4 font-poppins">
              Polls & Surveys
            </h1>
            <p className="text-lg text-blue-700 max-w-3xl mx-auto">
              Your voice matters! Participate in government polls and surveys to help shape policies and improve public services. 
              Every response contributes to better governance and community development.
            </p>
          </div>
          
          {/* Stats Overview */}
          <div className="grid grid-cols-4 gap-4 mt-6">
            <div className="bg-blue-600 text-white p-3">
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-lg font-bold">24</div>
                  <div className="text-xs text-blue-100">Active Polls</div>
                </div>
                <Vote className="w-5 h-5 text-blue-200" />
              </div>
            </div>
            <div className="bg-blue-600 text-white p-3">
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-lg font-bold">18</div>
                  <div className="text-xs text-blue-100">Active Surveys</div>
                </div>
                <BarChart3 className="w-5 h-5 text-blue-200" />
              </div>
            </div>
            <div className="bg-blue-600 text-white p-3">
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-lg font-bold">15.2K</div>
                  <div className="text-xs text-blue-100">Total Participants</div>
                </div>
                <Users className="w-5 h-5 text-blue-200" />
              </div>
            </div>
            <div className="bg-blue-600 text-white p-3">
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-lg font-bold">89%</div>
                  <div className="text-xs text-blue-100">Completion Rate</div>
                </div>
                <TrendingUp className="w-5 h-5 text-blue-200" />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* Controls Section */}
        <div className="bg-white border border-gray-200 p-3 mb-4">
          {/* Tabs */}
          <div className="flex flex-wrap gap-1 mb-3">
            {[
              { key: 'active', label: 'Active', icon: CheckCircle },
              { key: 'completed', label: 'Completed', icon: XCircle },
              { key: 'all', label: 'All', icon: BarChart3 }
            ].map(tab => (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex items-center gap-1 px-2 py-1 font-medium transition duration-200 text-sm ${
                  activeTab === tab.key
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                <tab.icon className="w-3 h-3" />
                {tab.label}
              </button>
            ))}
          </div>

          {/* Search and Filters */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {/* Search */}
            <div className="relative">
              <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
              <input
                type="text"
                placeholder="Search polls and surveys..."
                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>

            {/* Category Filter */}
            <div className="relative">
              <Filter className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
              <select
                value={filterCategory}
                onChange={(e) => setFilterCategory(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"
              >
                {categories.map(cat => (
                  <option key={cat.value} value={cat.value}>{cat.label}</option>
                ))}
              </select>
            </div>

            {/* Sort */}
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
            >
              <option value="recent">Most Recent</option>
              <option value="popular">Most Popular</option>
              <option value="ending">Ending Soon</option>
            </select>
          </div>
        </div>

        {/* Polls and Surveys Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {sortedPolls.map(item => (
            <div key={item.id} className="bg-white border border-gray-200 overflow-hidden hover:border-blue-300 transition duration-200">
              {/* Header */}
              <div className="p-4 border-b border-gray-100">
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className="px-2 py-1 text-xs font-medium border border-gray-300 bg-gray-100 text-gray-700">
                      {item.status === 'active' ? 'Active' : 'Completed'}
                    </span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-700">
                      {item.type === 'poll' ? 'Poll' : 'Survey'}
                    </span>
                  </div>
                  {item.status === 'active' && (
                    <div className="flex items-center gap-1 text-orange-600">
                      <Clock className="w-3 h-3" />
                      <span className="text-xs font-medium">
                        {getDaysRemaining(item.endDate)} days left
                      </span>
                    </div>
                  )}
                </div>
                
                <h3 className="text-lg font-semibold text-white bg-blue-600 p-2 mb-1 line-clamp-2">
                  {item.title}
                </h3>
                <p className="text-gray-600 text-sm line-clamp-2 mb-3">
                  {item.description}
                </p>

                <div className="flex items-center gap-4 text-xs text-gray-500">
                  <div className="flex items-center gap-1">
                    <Users className="w-3 h-3" />
                    <span>{item.totalVotes + item.totalResponses} participants</span>
                  </div>
                  <div className="flex items-center gap-1">
                    <Calendar className="w-3 h-3" />
                    <span>Ends {new Date(item.endDate).toLocaleDateString()}</span>
                  </div>
                </div>
              </div>

              {/* Content */}
              <div className="p-4">
                {item.type === 'poll' && item.options ? (
                  <div className="space-y-2">
                    {item.options.map(option => (
                      <div key={option.id}>
                        <button
                          onClick={() => item.status === 'active' && !item.myVote ? handleVote(item.id, option.id) : null}
                          disabled={item.status !== 'active' || item.myVote}
                          className={`w-full text-left p-3 border transition duration-200 relative overflow-hidden ${
                            item.myVote === option.id
                              ? 'border-blue-500 bg-blue-50 text-blue-900'
                              : item.status === 'active' && !item.myVote
                              ? 'border-gray-200 hover:border-blue-300 hover:bg-blue-50 cursor-pointer'
                              : 'border-gray-200 bg-gray-50'
                          }`}
                        >
                          {/* Background progress bar */}
                          <div 
                            className="absolute inset-0 bg-blue-100 transition-all duration-500"
                            style={{ width: `${option.percentage}%` }}
                          />
                          <div className="relative flex items-center justify-between">
                            <span className="font-medium text-sm">{option.text}</span>
                            <span className="text-sm text-gray-600 font-semibold">{option.percentage}%</span>
                          </div>
                        </button>
                      </div>
                    ))}
                    
                    {item.myVote && (
                      <div className="mt-3 p-2 bg-green-50 border border-green-200">
                        <div className="flex items-center gap-2 text-green-700">
                          <CheckCircle className="w-4 h-4" />
                          <span className="text-sm font-medium">Thank you for participating!</span>
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="space-y-2">
                    <div className="text-sm text-gray-600">
                      <strong>Survey Questions Preview:</strong>
                    </div>
                    <div className="space-y-1">
                      {item.questions?.slice(0, 3).map((question, idx) => (
                        <div key={idx} className="flex items-start gap-2 text-sm text-gray-700">
                          <span className="text-blue-600 font-medium">{idx + 1}.</span>
                          <span>{question}</span>
                        </div>
                      ))}
                      {item.questions?.length > 3 && (
                        <div className="text-xs text-gray-500 italic">
                          +{item.questions.length - 3} more questions...
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* Footer */}
              <div className="px-4 py-3 bg-gray-50 border-t border-gray-100">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4 text-xs text-gray-600">
                    <div className="flex items-center gap-1">
                      <Eye className="w-3 h-3" />
                      <span>{item.totalResponses} responses</span>
                    </div>
                    {item.type === 'survey' && (
                      <div className="flex items-center gap-1">
                        <MessageSquare className="w-3 h-3" />
                        <span>{item.questions?.length} questions</span>
                      </div>
                    )}
                  </div>
                  
                  {item.status === 'active' && (
                    <button className="flex items-center gap-2 px-3 py-1 bg-blue-600 text-white hover:bg-blue-700 transition duration-200 text-xs font-medium">
                      {item.type === 'poll' && !item.myVote ? 'Vote Now' : 
                       item.type === 'poll' && item.myVote ? 'View Results' : 
                       'Take Survey'}
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Empty State */}
        {sortedPolls.length === 0 && (
          <div className="text-center py-12">
            <div className="w-24 h-24 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
              <Vote className="w-12 h-12 text-gray-400" />
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">No polls or surveys found</h3>
            <p className="text-gray-600">Try adjusting your search criteria or check back later for new content.</p>
          </div>
        )}
      </div>

      <Footer />
    </div>
  );
};

export default PollsSurveys;