import React, { useState } from 'react';
import AdminLayout from '../../components/AdminLayout';
import { Pie, Bar, Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  ArcElement,
  Tooltip,
  Legend,
} from 'chart.js';
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  ArcElement,
  Tooltip,
  Legend
);
import DateFilterModal from '../../components/DateFilterModal';
import { Link } from 'react-router-dom';
import {
  TrendingUpIcon,
  TrendingDownIcon,
  UsersIcon,
  MessageSquareIcon,
  ClipboardListIcon,
  AlertTriangleIcon,
  CheckCircleIcon,
  BarChart3Icon,
  PieChartIcon,
  ActivityIcon,
  ArrowRightIcon,
  RefreshCwIcon,
  CalendarIcon,
} from 'lucide-react';

// ...existing StatCard and QuickActionCard components (same as before)
const StatCard = ({ title, value, change, changeType, icon, color, link }) => (
  <div className="bg-blue-700 rounded-lg shadow-md border border-gray-900 p-6 hover:shadow-lg transition-shadow">
    <div className="flex items-center justify-between">
      <div>
        <p className="text-sm font-medium text-gray-300 font-inter">{title}</p>
        <p className="text-2xl font-bold text-white font-poppins mt-1">{value}</p>
        {change && (
          <div className={`flex items-center mt-2 text-sm ${
            changeType === 'increase' ? 'text-green-400' : 'text-red-400'
          }`}>
            {changeType === 'increase' ? (
              <TrendingUpIcon className="w-4 h-4 mr-1" />
            ) : (
              <TrendingDownIcon className="w-4 h-4 mr-1" />
            )}
            <span className="font-medium">{change}</span>
            <span className="ml-1 text-gray-400">vs last month</span>
          </div>
        )}
      </div>
      <div className={`p-3 rounded-full ${color}`}>
        {icon}
      </div>
    </div>
    {link && (
      <Link 
        to={link} 
        className="inline-flex items-center mt-4 text-sm text-blue-400 hover:text-blue-200 font-medium"
      >
        View details
        <ArrowRightIcon className="w-4 h-4 ml-1" />
      </Link>
    )}
  </div>
);

const QuickActionCard = ({ title, description, icon, color, link }) => (
  <Link 
    to={link}
    className="block bg-blue-700 rounded-lg shadow-md border border-blue-900 p-6 hover:shadow-lg transition-all hover:-translate-y-1"
  >
    <div className="flex items-center space-x-4">
      <div className={`p-3 rounded-full bg-white`}>{icon}</div>
      <div>
        <h3 className="text-lg font-semibold text-white font-poppins">{title}</h3>
        <p className="text-sm text-blue-100 font-inter mt-1">{description}</p>
      </div>
    </div>
  </Link>
);

// Matrix Heatmap Component for Queries by Month vs Day of Week (Excel-like grid with green shades)
const MonthlyDailyQueriesHeatmap = () => {
  // Mock data: 2D matrix for months (rows) vs days of week (columns)
  // Rows: 12 Months
  // Columns: 7 Days (Mon-Sun), values represent average daily queries (pattern: higher on weekdays)
  // Data seeded to show trends: increasing over time, weekends lower
  const data = [
    // Oct 24
    [180, 200, 210, 190, 220, 150, 140],
    // Nov 24
    [190, 210, 220, 200, 230, 160, 150],
    // Dec 24
    [220, 240, 250, 230, 260, 180, 170],
    // Jan 25
    [210, 230, 240, 220, 250, 170, 160],
    // Feb 25
    [240, 260, 270, 250, 280, 190, 180],
    // Mar 25
    [250, 270, 280, 260, 290, 200, 190],
    // Apr 25
    [230, 250, 260, 240, 270, 180, 170],
    // May 25
    [280, 300, 310, 290, 320, 220, 210],
    // Jun 25
    [260, 280, 290, 270, 300, 200, 190],
    // Jul 25
    [290, 310, 320, 300, 330, 230, 220],
    // Aug 25
    [270, 290, 300, 280, 310, 210, 200],
    // Sep 25
    [300, 320, 330, 310, 340, 240, 230],
  ];

  const months = ['Oct 24', 'Nov 24', 'Dec 24', 'Jan 25', 'Feb 25', 'Mar 25', 'Apr 25', 'May 25', 'Jun 25', 'Jul 25', 'Aug 25', 'Sep 25'];
  const daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  // Normalize all values to levels 0-5 (global min/max across matrix)
  const allValues = data.flat();
  const minValue = Math.min(...allValues);
  const maxValue = Math.max(...allValues);
  const getLevel = (value) => Math.round(((value - minValue) / (maxValue - minValue)) * 5);

  const getColor = (level) => {
    const greenShades = [
      '#f0fdf4', // 0: emerald-50
      '#d1fae5', // 1: emerald-100
      '#a7f3d0', // 2: emerald-200
      '#6ee7b7', // 3: emerald-300
      '#34d399', // 4: emerald-400
      '#10b981', // 5: emerald-500
    ];
    return greenShades[level] || greenShades[0];
  };

  const getTooltipText = (month, day, value, level) => `${month} - ${day}: ${value.toLocaleString()} avg queries (Level ${level})`;

  const [hoveredCell, setHoveredCell] = useState({ row: null, col: null });

  const renderHeaderRow = () => (
    <div className="flex border-b border-gray-200">
      <div className="w-32 h-12 flex items-center justify-center bg-gray-50 border-r border-gray-200 text-xs font-semibold text-gray-600 uppercase tracking-wide"></div>
      {daysOfWeek.map((day, colIndex) => (
        <div
          key={day}
          className="flex-1 h-12 flex items-center justify-center border-r border-gray-200 text-xs font-semibold text-gray-700 bg-gray-50 last:border-r-0"
        >
          {day}
        </div>
      ))}
    </div>
  );

  const renderDataRow = (rowData, rowIndex) => (
    <div className="flex border-b border-gray-200 last:border-b-0">
      <div className="w-32 h-12 flex items-center justify-start px-3 bg-gray-50 border-r border-gray-200 text-sm font-medium text-gray-700">
        {months[rowIndex]}
      </div>
      {rowData.map((value, colIndex) => {
        const level = getLevel(value);
        const isHovered = hoveredCell.row === rowIndex && hoveredCell.col === colIndex;
        return (
          <div
            key={`${rowIndex}-${colIndex}`}
            className={`relative flex-1 h-12 flex flex-col items-center justify-center cursor-pointer transition-all duration-200 group border-r border-gray-200 last:border-r-0 ${
              isHovered ? 'scale-[1.02] shadow-lg ring-2 ring-emerald-400/30 z-10' : 'hover:scale-[1.01] hover:shadow-md'
            }`}
            style={{ backgroundColor: getColor(level) }}
            onMouseEnter={() => setHoveredCell({ row: rowIndex, col: colIndex })}
            onMouseLeave={() => setHoveredCell({ row: null, col: null })}
          >
            <span
              className={`text-xs font-mono font-bold transition-all duration-200 text-center ${
                level >= 4 ? 'text-white drop-shadow-sm' : 'text-gray-800'
              } ${isHovered ? 'text-sm' : ''}`}
            >
              {value.toLocaleString()}
            </span>
            {isHovered && (
              <div className="absolute -top-2 left-1/2 transform -translate-x-1/2 bg-emerald-800 text-white text-xs px-3 py-2 rounded-md whitespace-nowrap shadow-xl z-20 border border-emerald-600 min-w-max">
                <div className="font-medium">{getTooltipText(months[rowIndex], daysOfWeek[colIndex], value, level)}</div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );

  const renderLegend = () => (
    <div className="mt-6 pt-4 border-t border-gray-200">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div className="flex items-center space-x-3 text-sm">
          <span className="text-gray-600 font-medium">Query Intensity:</span>
          {Array.from({ length: 6 }, (_, i) => (
            <div key={i} className="flex items-center space-x-1">
              <div
                className="w-4 h-4 rounded border"
                style={{ backgroundColor: getColor(i) }}
              />
              <span className="text-gray-700">{i}</span>
            </div>
          ))}
        </div>
        <div className="text-sm text-gray-500">
          <span className="font-medium text-gray-700">Range:</span>{' '}
          {minValue.toLocaleString()} - {maxValue.toLocaleString()} avg queries/day
        </div>
      </div>
    </div>
  );

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 w-full">
      <div className="flex items-center justify-between mb-5">
        <h3 className="text-lg font-semibold text-gray-900 font-poppins flex items-center gap-2">
          <BarChart3Icon className="w-5 h-5 text-emerald-600" />
          Queries Heatmap: Months vs Days of Week
        </h3>
        <div className="flex items-center gap-2 text-xs text-gray-500">
          <span>Low</span>
          <div className="flex-1 h-1 bg-gradient-to-r from-emerald-300 via-emerald-500 to-emerald-700 rounded-full"></div>
          <span>High</span>
        </div>
      </div>

      {/* Heatmap Matrix */}
      <div className="overflow-x-auto max-h-96">
        <div className="min-w-max">
          {renderHeaderRow()}
          {data.map((rowData, rowIndex) => renderDataRow(rowData, rowIndex))}
        </div>
      </div>

      {renderLegend()}
    </div>
  );
};

// Line Chart Component for Polls Answered Over Months
const PollsAnsweredLineChart = () => {
  // Mock data for polls answered per month (last 12 months)
  const pollsData = {
    labels: ['Oct 24', 'Nov 24', 'Dec 24', 'Jan 25', 'Feb 25', 'Mar 25', 'Apr 25', 'May 25', 'Jun 25', 'Jul 25', 'Aug 25', 'Sep 25'],
    datasets: [
      {
        label: 'Polls Answered',
        data: [500, 550, 700, 600, 750, 850, 650, 900, 800, 950, 850, 1000],
        borderColor: '#10b981',
        backgroundColor: 'rgba(16, 185, 129, 0.1)',
        borderWidth: 3,
        fill: true,
        tension: 0.4,
        pointBackgroundColor: '#10b981',
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 6,
        pointHoverRadius: 8,
      },
    ],
  };

  const pollsOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        ticks: {
          font: { family: 'Inter, sans-serif', size: 12 },
          color: '#6b7280',
        },
        grid: {
          color: '#f3f4f6',
        },
      },
      x: {
        ticks: {
          font: { family: 'Inter, sans-serif', size: 12 },
          color: '#6b7280',
        },
        grid: {
          display: false,
        },
      },
    },
    interaction: {
      intersect: false,
      mode: 'index',
    },
  };

  return (
    <div className="bg-white rounded-lg shadow-md border border-gray-200 p-6">
      <h3 className="text-lg font-semibold text-gray-900 font-poppins mb-4">Polls Answered Over Time</h3>
      <div style={{ height: 300 }} className="flex items-center justify-center">
        <Line data={pollsData} options={pollsOptions} />
      </div>
      <p className="text-sm text-gray-500 mt-3 text-center font-inter">
        Steady growth in poll participation across the past year
      </p>
    </div>
  );
};

export default function AdminDashboard() {
  const [dateFilterOpen, setDateFilterOpen] = useState(false);
  const [dateRange, setDateRange] = useState({ start: '', end: '' });

  // ...existing mock data
  const stats = {
    totalCitizens: 12543,
    citizenChange: '+8.2%',
    activeComplaints: 156,
    complaintChange: '-12.4%',
    activePolls: 8,
    pollChange: '+2.1%',
    resolvedToday: 23,
    resolvedChange: '+15.3%'
  };

  const recentActivity = [
    { id: 1, type: 'complaint', message: 'New complaint submitted about road conditions', time: '5 minutes ago', status: 'new' },
    { id: 2, type: 'poll', message: 'Health Policy Survey reached 1000 responses', time: '15 minutes ago', status: 'milestone' },
    { id: 3, type: 'user', message: 'New user registration from Kampala region', time: '23 minutes ago', status: 'info' },
    { id: 4, type: 'complaint', message: 'Complaint #1234 marked as resolved', time: '1 hour ago', status: 'resolved' },
    { id: 5, type: 'system', message: 'Daily backup completed successfully', time: '2 hours ago', status: 'success' }
  ];

  const urgentIssues = [
    { id: 1, title: 'High Priority Complaint - Ministry of Health', time: '30 mins ago', severity: 'high' },
    { id: 2, title: 'System Performance Alert', time: '1 hour ago', severity: 'medium' },
    { id: 3, title: 'Failed User Registration Attempts', time: '2 hours ago', severity: 'low' }
  ];

  // Mock data for bar chart: Queries per month (last 12 months)
  const monthlyQueriesData = {
    labels: ['Oct 24', 'Nov 24', 'Dec 24', 'Jan 25', 'Feb 25', 'Mar 25', 'Apr 25', 'May 25', 'Jun 25', 'Jul 25', 'Aug 25', 'Sep 25'],
    datasets: [
      {
        label: 'Queries',
        data: [1200, 1450, 1800, 1600, 1900, 2100, 1750, 2200, 1950, 2300, 2050, 2400],
        backgroundColor: '#3b82f6',
        borderColor: '#1d4ed8',
        borderWidth: 1,
      },
    ],
  };

  const monthlyQueriesOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        ticks: {
          font: { family: 'Inter, sans-serif', size: 12 },
          color: '#6b7280',
        },
        grid: {
          color: '#f3f4f6',
        },
      },
      x: {
        ticks: {
          font: { family: 'Inter, sans-serif', size: 12 },
          color: '#6b7280',
        },
        grid: {
          display: false,
        },
      },
    },
  };

  const handleDateFilterApply = (start, end) => {
    setDateRange({ start, end });
    // Fetch and filter dashboard data based on date range here
  };

  return (
    <AdminLayout>
      {/* Dashboard Content */}
      <main className="flex-1 overflow-y-auto p-6">
        {/* Header */}
        <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">Admin Dashboard</h1>
              <p className="text-gray-600 font-inter mt-1">Monitor and manage the Citizen Portal</p>
            </div>
            <div className="flex items-center space-x-4 mt-4 sm:mt-0">
              <button
                onClick={() => setDateFilterOpen(true)}
                className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-inter"
              >
                <BarChart3Icon className="w-4 h-4 mr-2" />
                Filter by Date
              </button>
              {dateRange.start && dateRange.end && (
                <div className="text-sm text-gray-500 font-inter">
                  Showing: {dateRange.start} to {dateRange.end}
                </div>
              )}
            </div>
            {dateFilterOpen && (
              <DateFilterModal
                onClose={() => setDateFilterOpen(false)}
                onApply={handleDateFilterApply}
                defaultStart={dateRange.start}
                defaultEnd={dateRange.end}
              />
            )}
          </div>

          {/* Stats Grid & Charts */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <div className="lg:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6">
              <StatCard
                title="Total Citizens"
                value={stats.totalCitizens.toLocaleString()}
                change={stats.citizenChange}
                changeType="increase"
                icon={<UsersIcon className="w-6 h-6 text-white" />}
                color="bg-blue-500"
                link="/admin/users/citizens"
              />
              <StatCard
                title="Active Complaints"
                value={stats.activeComplaints}
                change={stats.complaintChange}
                changeType="decrease"
                icon={<MessageSquareIcon className="w-6 h-6 text-white" />}
                color="bg-orange-500"
                link="/admin/complaints"
              />
              <StatCard
                title="Active Polls"
                value={stats.activePolls}
                change={stats.pollChange}
                changeType="increase"
                icon={<ClipboardListIcon className="w-6 h-6 text-white" />}
                color="bg-green-500"
                link="/admin/polls-surveys"
              />
              <StatCard
                title="Resolved Today"
                value={stats.resolvedToday}
                change={stats.resolvedChange}
                changeType="increase"
                icon={<CheckCircleIcon className="w-6 h-6 text-white" />}
                color="bg-purple-500"
                link="/admin/complaints/resolved"
              />
            </div>
            {/* Sample Pie Chart */}
            <div className="bg-white rounded-lg shadow-md border border-gray-200 flex flex-col items-center justify-center p-6">
              <h3 className="text-lg font-semibold text-gray-900 font-poppins mb-2">Complaints by Category</h3>
              <div style={{ width: 260, height: 260 }} className="flex items-center justify-center">
                <Pie
                  data={{
                    labels: ['Roads', 'Health', 'Water', 'Education', 'Other'],
                    datasets: [
                      {
                        label: 'Complaints',
                        data: [32, 21, 15, 18, 9],
                        backgroundColor: [
                          '#2563eb', // blue
                          '#f59e42', // orange
                          '#10b981', // green
                          '#a78bfa', // purple
                          '#fbbf24', // yellow
                        ],
                        borderWidth: 1,
                      },
                    ],
                  }}
                  options={{
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                      legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                          font: { family: 'Inter, sans-serif', size: 13 },
                          color: '#374151',
                          boxWidth: 16,
                          padding: 12,
                        },
                      },
                    },
                  }}
                />
              </div>
            </div>
          </div>

          {/* Quick Actions */}
          <div className="mb-8">
            <h2 className="text-xl font-semibold text-gray-900 font-poppins mb-4">Quick Actions</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <QuickActionCard
                title="Create Poll"
                description="Launch a new poll or survey"
                icon={<ClipboardListIcon className="w-6 h-6 text-blue-700" />}
                link="/admin/polls-surveys/create"
              />
              <QuickActionCard
                title="View Complaints"
                description="Manage pending complaints"
                icon={<MessageSquareIcon className="w-6 h-6 text-blue-700" />}
                link="/admin/complaints/pending"
              />
              <QuickActionCard
                title="User Management"
                description="Add or manage users"
                icon={<UsersIcon className="w-6 h-6 text-blue-700" />}
                link="/admin/users"
              />
              <QuickActionCard
                title="Analytics"
                description="View detailed reports"
                icon={<BarChart3Icon className="w-6 h-6 text-blue-700" />}
                link="/admin/analytics"
              />
            </div>
          </div>

          {/* Content Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            {/* Recent Activity */}
            <div className="lg:col-span-2">
              <div className="bg-white rounded-lg shadow-md border border-gray-200 p-14">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-gray-900 font-poppins">Recent Activity</h3>
                  <Link 
                    to="/admin/activity"
                    className="text-sm text-blue-600 hover:text-blue-800 font-medium"
                  >
                    View all
                  </Link>
                </div>
                <div className="space-y-4">
                  {recentActivity.map((activity) => (
                    <div key={activity.id} className="flex items-start space-x-3 p-3 rounded-lg hover:bg-gray-50 transition-colors">
                      <div className={`p-2 rounded-full ${
                        activity.status === 'new' ? 'bg-blue-100' :
                        activity.status === 'resolved' ? 'bg-green-100' :
                        activity.status === 'milestone' ? 'bg-purple-100' :
                        'bg-gray-100'
                      }`}>
                        {activity.type === 'complaint' && <MessageSquareIcon className="w-4 h-4 text-blue-600" />}
                        {activity.type === 'poll' && <ClipboardListIcon className="w-4 h-4 text-purple-600" />}
                        {activity.type === 'user' && <UsersIcon className="w-4 h-4 text-green-600" />}
                        {activity.type === 'system' && <ActivityIcon className="w-4 h-4 text-gray-600" />}
                      </div>
                      <div className="flex-1">
                        <p className="text-sm text-gray-900 font-medium font-inter">{activity.message}</p>
                        <p className="text-xs text-gray-500 mt-1">{activity.time}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Urgent Issues */}
            <div>
              <div className="bg-white rounded-lg shadow-md border border-gray-200 p-6">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-gray-900 font-poppins">Urgent Issues</h3>
                  <AlertTriangleIcon className="w-5 h-5 text-orange-500" />
                </div>
                <div className="space-y-3">
                  {urgentIssues.map((issue) => (
                    <div key={issue.id} className="p-1 rounded-lg border-2 hover:bg-gray-50 transition-colors">
                      <h4 className="text-sm font-medium text-gray-900 font-inter">{issue.title}</h4>
                      <div className="flex items-center justify-between mt-2">
                        <p className="text-xs text-gray-500">{issue.time}</p>
                        <span className={`px-2 py-1 text-xs rounded-full ${
                          issue.severity === 'high' ? 'bg-red-100 text-red-800' :
                          issue.severity === 'medium' ? 'bg-orange-100 text-orange-800' :
                          'bg-yellow-100 text-yellow-800'
                        }`}>
                          {issue.severity}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
                <Link 
                  to="/admin/issues"
                  className="block mt-4 text-center text-sm text-blue-600 hover:text-blue-800 font-medium"
                >
                  View all issues
                </Link>
              </div>

              {/* Quick Stats */}
              <div className="bg-white rounded-lg shadow-md border border-gray-200 p-2 mt-6">
                <h3 className="text-lg font-semibold text-gray-900 font-poppins mb-4">Today's Summary</h3>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 font-inter">New Registrations</span>
                    <span className="text-sm font-medium text-gray-900">47</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 font-inter">Complaints Resolved</span>
                    <span className="text-sm font-medium text-gray-900">23</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 font-inter">Poll Responses</span>
                    <span className="text-sm font-medium text-gray-900">341</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 font-inter">System Uptime</span>
                    <span className="text-sm font-medium text-green-600">99.9%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* New Analytics Row: Line Graph and Bar Graph */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            {/* Line Graph: Polls Answered */}
            <PollsAnsweredLineChart />

            {/* Bar Graph: Queries per Month */}
            <div className="bg-white rounded-lg shadow-md border border-gray-200 p-6">
              <h3 className="text-lg font-semibold text-gray-900 font-poppins mb-4">Queries per Month</h3>
              <div style={{ height: 300 }} className="flex items-center justify-center">
                <Bar data={monthlyQueriesData} options={monthlyQueriesOptions} />
              </div>
              <p className="text-sm text-gray-500 mt-3 text-center font-inter">
                Trend showing increasing query volume over the past year
              </p>
            </div>
          </div>

          {/* New Full-Width Row: Matrix Heatmap for Queries: Months vs Days */}
          <div className="grid grid-cols-1 gap-6">
            <MonthlyDailyQueriesHeatmap />
          </div>
        </main>
    </AdminLayout>
  );
}