import React, { useState, useEffect } from 'react';
import { Breadcrumb, BreadcrumbItem, Card, Row, Col } from 'react-bootstrap';
import { AuthService, CustomerService, TransRoutesService } from '../../services';
import moment from 'moment';
import { CUSTOMER_TYPE, PERSONAL_ROUTE_STATUS, CUSTOMER_JOIN_REASON, CUSTOMER_JOIN_REASON_TEXT, CUSTOMER_DISCHARGE_REASON, CUSTOMER_DISCHARGE_REASON_TEXT } from '../../shared';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
} from 'chart.js';
import { Line, Doughnut } from 'react-chartjs-2';
import './AdminView.css';

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
);

const AdminView = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [customers, setCustomers] = useState([]);
  const [selectedWeek, setSelectedWeek] = useState('this-week');
  const [selectedMonth, setSelectedMonth] = useState('this-month');
  const [selectedDischargeWeek, setSelectedDischargeWeek] = useState('this-week');
  const [memberTrendData, setMemberTrendData] = useState({
    labels: [],
    datasets: []
  });
  const [attendanceTrendData, setAttendanceTrendData] = useState({
    labels: [],
    datasets: []
  });
  const [paySourceData, setPaySourceData] = useState({
    labels: [],
    datasets: []
  });
  const [newAdmissionsData, setNewAdmissionsData] = useState({
    labels: [],
    datasets: []
  });
  const [dischargeReasonsData, setDischargeReasonsData] = useState({
    labels: [],
    datasets: []
  });
  
  // Mock data for demonstration - replace with actual API calls
  const [statsData, setStatsData] = useState({
    totalMembers: 0,
    totalMembersIncreaseRate: 0,
    todayAttendance: 0,
    todayAttendanceChangeRate: 0,
    todayAttendanceTrend: '',
    newMembersThisMonth: 0,
    newMembersChangeRate: 0,
    newMembersTrend: '',
    memberDischargesThisMonth: 0,
    dischargesChangeRate: 0,
    dischargesTrend: ''
  });

  useEffect(() => {
    // Check if user has admin access
    if (!AuthService.canAccessLegacySystem()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change an admin account to login.');
      AuthService.logout();
      window.location.href = '/login';
      return;
    }
    
    // Load initial data
    loadCustomerData();
    setIsLoading(false);
  }, []);

  const loadCustomerData = async () => {
    try {
      // Fetch all customers
      const customersData = await CustomerService.getAllCustomers();
      const allCustomers = customersData.data;
      setCustomers(allCustomers);

      // Calculate total active members
      const activeCustomers = allCustomers.filter(customer => customer.status === 'active');
      const totalMembers = activeCustomers.length;

      // Generate member trend data for the selected week
      generateMemberTrendData(allCustomers, selectedWeek);
      generateAttendanceTrendData(selectedWeek);
      generatePaySourceData(allCustomers);
      generateNewAdmissionsData(allCustomers, selectedMonth);
      generateDischargeReasonsData(allCustomers, selectedDischargeWeek);

      // Calculate new members this month
      const currentMonth = moment();
      const newMembersThisMonth = allCustomers.filter(customer => 
        moment(customer.create_date).isSame(currentMonth, 'month') && customer.status === 'active'
      ).length;

      // Calculate new members last month
      const lastMonth = moment().subtract(1, 'month');
      const newMembersLastMonth = allCustomers.filter(customer => 
        moment(customer.create_date).isSame(lastMonth, 'month') && customer.status === 'active'
      ).length;

      // Calculate new members change rate
      let newMembersChangeRate = 0;
      let newMembersTrend = '';
      if (newMembersLastMonth > 0) {
        const percentageChange = ((newMembersThisMonth - newMembersLastMonth) / newMembersLastMonth) * 100;
        newMembersChangeRate = Math.abs(percentageChange);
        newMembersTrend = percentageChange >= 0 ? 'increase' : 'decrease';
      } else if (newMembersThisMonth > 0) {
        newMembersChangeRate = 100;
        newMembersTrend = 'increase';
      }

      // Calculate member discharges this month
      const currentMonthDischarge = moment();
      const memberDischargesThisMonth = allCustomers.filter(customer => {
        if (!customer.discharge_date) return false;
        const dischargeDate = moment(customer.discharge_date, 'MM/DD/YYYY');
        return dischargeDate.isSame(currentMonthDischarge, 'month');
      }).length;

      // Calculate member discharges last month
      const lastMonthDischarge = moment().subtract(1, 'month');
      const memberDischargesLastMonth = allCustomers.filter(customer => {
        if (!customer.discharge_date) return false;
        const dischargeDate = moment(customer.discharge_date, 'MM/DD/YYYY');
        return dischargeDate.isSame(lastMonthDischarge, 'month');
      }).length;

      // Calculate discharges change rate
      let dischargesChangeRate = 0;
      let dischargesTrend = '';
      if (memberDischargesLastMonth > 0) {
        const percentageChange = ((memberDischargesThisMonth - memberDischargesLastMonth) / memberDischargesLastMonth) * 100;
        dischargesChangeRate = Math.abs(percentageChange);
        dischargesTrend = percentageChange >= 0 ? 'increase' : 'decrease';
      } else if (memberDischargesThisMonth > 0) {
        dischargesChangeRate = 100;
        dischargesTrend = 'increase';
      }

      // Calculate increase rate
      const currentMembersMinusNew = totalMembers - newMembersThisMonth;
      const increaseRate = currentMembersMinusNew > 0 
        ? ((newMembersThisMonth / currentMembersMinusNew) * 100).toFixed(1)
        : newMembersThisMonth > 0 ? 100 : 0;

      // Calculate today's attendance
      const today = moment().format('MM/DD/YYYY');
      const todayRoutesData = await TransRoutesService.getAll(today);
      const todayInboundRoutes = todayRoutesData.data.filter(route => route.type === 'inbound');
      const todayAllCustomers = TransRoutesService.getAllCustomersFromRoutes(todayInboundRoutes, []);
      const todayAttendance = todayAllCustomers.filter(customer => 
        customer.customer_route_status !== PERSONAL_ROUTE_STATUS.UNEXPECTED_ABSENT && 
        customer.customer_route_status !== PERSONAL_ROUTE_STATUS.SCHEDULED_ABSENT
      ).length;

      // Calculate yesterday's attendance
      const yesterday = moment().subtract(1, 'day').format('MM/DD/YYYY');
      const yesterdayRoutesData = await TransRoutesService.getAll(yesterday);
      const yesterdayInboundRoutes = yesterdayRoutesData.data.filter(route => route.type === 'inbound');
      const yesterdayAllCustomers = TransRoutesService.getAllCustomersFromRoutes(yesterdayInboundRoutes, []);
      const yesterdayAttendance = yesterdayAllCustomers.filter(customer => 
        customer.customer_route_status !== PERSONAL_ROUTE_STATUS.UNEXPECTED_ABSENT && 
        customer.customer_route_status !== PERSONAL_ROUTE_STATUS.SCHEDULED_ABSENT
      ).length;

      // Calculate attendance change rate
      let attendanceChangeRate = 0;
      let attendanceTrend = '';
      if (yesterdayAttendance > 0) {
        const percentageChange = ((todayAttendance - yesterdayAttendance) / yesterdayAttendance) * 100;
        attendanceChangeRate = Math.abs(percentageChange);
        attendanceTrend = percentageChange >= 0 ? 'increase' : 'decrease';
      } else if (todayAttendance > 0) {
        attendanceChangeRate = 100;
        attendanceTrend = 'increase';
      }

      setStatsData(prevData => ({
        ...prevData,
        totalMembers,
        totalMembersIncreaseRate: parseFloat(increaseRate),
        newMembersThisMonth,
        newMembersChangeRate,
        newMembersTrend,
        todayAttendance,
        todayAttendanceChangeRate: attendanceChangeRate,
        todayAttendanceTrend: attendanceTrend,
        memberDischargesThisMonth,
        dischargesChangeRate,
        dischargesTrend
      }));

    } catch (error) {
      console.error('Error fetching customer data:', error);
    }
  };

  // Generate week options for the past 52 weeks
  const generateWeekOptions = () => {
    const options = [];
    const currentWeek = moment().startOf('week');
    
    // This week
    options.push({
      value: 'this-week',
      label: 'This Week'
    });
    
    // Past 52 weeks
    for (let i = 1; i <= 52; i++) {
      const weekStart = moment().subtract(i, 'weeks').startOf('week');
      const weekEnd = moment().subtract(i, 'weeks').endOf('week');
      options.push({
        value: `week-${i}`,
        label: `${weekStart.format('MMM DD')} - ${weekEnd.format('MMM DD, YYYY')}`
      });
    }
    
    return options;
  };

  // Generate month options for the past 12 months
  const generateMonthOptions = () => {
    const options = [];
    
    // This month
    options.push({
      value: 'this-month',
      label: 'This Month'
    });
    
    // Past 12 months
    for (let i = 1; i <= 12; i++) {
      const month = moment().subtract(i, 'months');
      options.push({
        value: `month-${i}`,
        label: month.format('MMMM YYYY')
      });
    }
    
    return options;
  };

  // Generate member trend data for the selected week
  const generateMemberTrendData = (allCustomers, weekSelection) => {
    let startDate, endDate;
    
    if (weekSelection === 'this-week') {
      startDate = moment().startOf('week');
      endDate = moment().endOf('week');
    } else {
      const weekNumber = parseInt(weekSelection.split('-')[1]);
      startDate = moment().subtract(weekNumber, 'weeks').startOf('week');
      endDate = moment().subtract(weekNumber, 'weeks').endOf('week');
    }
    
    const labels = [];
    const data = [];
    
    // Generate data for each day of the week
    for (let i = 0; i < 7; i++) {
      const currentDate = moment(startDate).add(i, 'days');
      labels.push(currentDate.format('MMM DD'));
      
      // Count active members as of this date (create_date is before or on this date)
      const activeMembersOnDate = allCustomers.filter(customer => {
        if (customer.status !== 'active') return false;
        
        // If customer was created after this date, they weren't a member yet
        if (customer.create_date && moment(customer.create_date).isAfter(currentDate)) {
          return false;
        }
        
        // If customer was discharged before or on this date, they're no longer a member
        if (customer.discharge_date && moment(customer.discharge_date, 'MM/DD/YYYY').isSameOrBefore(currentDate)) {
          return false;
        }
        
        return true;
      }).length;
      
      data.push(activeMembersOnDate);
    }
    
    // Calculate average
    const average = Math.round(data.reduce((sum, val) => sum + val, 0) / data.length);
    
    setMemberTrendData({
      labels,
      datasets: [
        {
          label: 'Active Members',
          data,
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.5)',
          tension: 0.1,
          pointRadius: 6,
          pointHoverRadius: 8
        }
      ],
      average
    });
  };

  // Generate attendance trend data for the selected week
  const generateAttendanceTrendData = async (weekSelection) => {
    let startDate, endDate;
    
    if (weekSelection === 'this-week') {
      startDate = moment().startOf('week');
      endDate = moment().endOf('week');
    } else {
      const weekNumber = parseInt(weekSelection.split('-')[1]);
      startDate = moment().subtract(weekNumber, 'weeks').startOf('week');
      endDate = moment().subtract(weekNumber, 'weeks').endOf('week');
    }
    
    const labels = [];
    const data = [];
    
    // Generate data for each day of the week
    for (let i = 0; i < 7; i++) {
      const currentDate = moment(startDate).add(i, 'days');
      const dateString = currentDate.format('MM/DD/YYYY');
      labels.push(currentDate.format('MMM DD'));
      
      try {
        // Fetch routes for this specific date
        const routesData = await TransRoutesService.getAll(dateString);
        const inboundRoutes = routesData.data.filter(route => route.type === 'inbound');
        const allCustomers = TransRoutesService.getAllCustomersFromRoutes(inboundRoutes, []);
        
        // Count attendance (customers who are not scheduled or unexpected absent)
        const attendanceCount = allCustomers.filter(customer => 
          customer.customer_route_status !== PERSONAL_ROUTE_STATUS.UNEXPECTED_ABSENT && 
          customer.customer_route_status !== PERSONAL_ROUTE_STATUS.SCHEDULED_ABSENT
        ).length;
        
        data.push(attendanceCount);
      } catch (error) {
        console.error(`Error fetching routes for ${dateString}:`, error);
        data.push(0);
      }
    }
    
    // Calculate average
    const average = Math.round(data.reduce((sum, val) => sum + val, 0) / data.length);
    
    setAttendanceTrendData({
      labels,
      datasets: [
        {
          label: 'Attendance',
          data,
          borderColor: 'rgb(255, 99, 132)',
          backgroundColor: 'rgba(255, 99, 132, 0.5)',
          tension: 0.1,
          pointRadius: 6,
          pointHoverRadius: 8
        }
      ],
      average
    });
  };

  // Generate pay source distribution data
  const generatePaySourceData = (allCustomers) => {
    console.log('generatePaySourceData called with:', allCustomers?.length, 'customers');
    
    const activeCustomers = allCustomers.filter(customer => customer.status === 'active');
    console.log('Active customers:', activeCustomers.length);
    
    const totalActive = activeCustomers.length;
    
    const paySourceCounts = {
      'Medicaid': 0,
      'Medicare': 0,
      'Self Pay': 0,
      'Other': 0
    };
    
    activeCustomers.forEach(customer => {
      if (customer.medicaid_number) {
        paySourceCounts['Medicaid']++;
      } else if (customer.medicare_number) {
        paySourceCounts['Medicare']++;
      } else if (customer.type === 'selfPayMember') {
        paySourceCounts['Self Pay']++;
      } else {
        paySourceCounts['Other']++;
      }
    });
    
    console.log('Pay source counts:', paySourceCounts);
    
    const labels = Object.keys(paySourceCounts);
    const data = Object.values(paySourceCounts);
    const percentages = data.map(count => totalActive > 0 ? Math.round((count / totalActive) * 100) : 0);
    
    console.log('Labels:', labels, 'Data:', data, 'Percentages:', percentages);
    
    // Generate colors for each pay source
    const colors = [
      'rgb(255, 99, 132)',   // Red for Medicaid
      'rgb(54, 162, 235)',   // Blue for Medicare
      'rgb(255, 205, 86)',   // Yellow for Self Pay
      'rgb(75, 192, 192)'    // Teal for Other
    ];
    
    const newPaySourceData = {
      labels,
      datasets: [{
        data,
        backgroundColor: colors,
        borderColor: colors.map(color => color.replace('rgb', 'rgba').replace(')', ', 0.8)')),
        borderWidth: 2,
        hoverOffset: 4
      }],
      percentages,
      totalActive
    };
    
    console.log('Setting paySourceData:', newPaySourceData);
    setPaySourceData(newPaySourceData);
  };

  // Generate new admissions distribution data
  const generateNewAdmissionsData = (allCustomers, monthSelection = 'this-month') => {
    console.log('generateNewAdmissionsData called with:', allCustomers?.length, 'customers, month:', monthSelection);
    
    // Determine the target month
    let targetMonth;
    if (monthSelection === 'this-month') {
      targetMonth = moment();
    } else {
      const monthNumber = parseInt(monthSelection.split('-')[1]);
      targetMonth = moment().subtract(monthNumber, 'months');
    }
    
    console.log('Target month:', targetMonth.format('MMMM YYYY'));
    
    // Filter customers by the selected month and active status
    const customersInMonth = allCustomers.filter(customer => 
      moment(customer.create_date).isSame(targetMonth, 'month') && customer.status === 'active'
    );
    
    console.log('Customers in selected month:', customersInMonth.length);
    
    const totalInMonth = customersInMonth.length;
    
    const joinReasonCounts = {
      'Friend or Family Referral': 0,
      'Social Worker Referral': 0,
      'Social Media (Instagram, etc)': 0,
      'Event': 0,
      'Other': 0,
      'N/A': 0
    };
    
    customersInMonth.forEach(customer => {
      if (customer.join_reason) {
        const reasonText = CUSTOMER_JOIN_REASON_TEXT[customer.join_reason];
        if (reasonText) {
          joinReasonCounts[reasonText]++;
        } else {
          joinReasonCounts['N/A']++;
        }
      } else {
        joinReasonCounts['N/A']++;
      }
    });
    
    console.log('Join reason counts:', joinReasonCounts);
    
    const labels = Object.keys(joinReasonCounts);
    const data = Object.values(joinReasonCounts);
    const percentages = data.map(count => totalInMonth > 0 ? Math.round((count / totalInMonth) * 100) : 0);
    
    console.log('Labels:', labels, 'Data:', data, 'Percentages:', percentages);
    
    // Generate colors for each join reason
    const colors = [
      'rgb(255, 99, 132)',   // Red for Friend or Family Referral
      'rgb(54, 162, 235)',   // Blue for Social Worker Referral
      'rgb(255, 205, 86)',   // Yellow for Social Media
      'rgb(75, 192, 192)',   // Teal for Event
      'rgb(153, 102, 255)',  // Purple for Other
      'rgb(201, 203, 207)'   // Gray for N/A
    ];
    
    const newAdmissionsData = {
      labels,
      datasets: [{
        data,
        backgroundColor: colors,
        borderColor: colors.map(color => color.replace('rgb', 'rgba').replace(')', ', 0.8)')),
        borderWidth: 2,
        hoverOffset: 4
      }],
      percentages,
      totalInMonth
    };
    
    console.log('Setting newAdmissionsData:', newAdmissionsData);
    setNewAdmissionsData(newAdmissionsData);
  };

  // Generate discharge reasons distribution data
  const generateDischargeReasonsData = (allCustomers, weekSelection = 'this-week') => {
    console.log('generateDischargeReasonsData called with:', allCustomers?.length, 'customers, week:', weekSelection);
    
    // Determine the target week
    let startDate, endDate;
    if (weekSelection === 'this-week') {
      startDate = moment().startOf('week');
      endDate = moment().endOf('week');
    } else {
      const weekNumber = parseInt(weekSelection.split('-')[1]);
      startDate = moment().subtract(weekNumber, 'weeks').startOf('week');
      endDate = moment().subtract(weekNumber, 'weeks').endOf('week');
    }
    
    console.log('Target week:', startDate.format('MMM DD') + ' - ' + endDate.format('MMM DD, YYYY'));
    
    // Filter customers whose type is discharged and discharge_date is within the selected week
    const dischargedCustomers = allCustomers.filter(customer => {
      if (customer.type !== 'discharged') return false;
      if (!customer.discharge_date) return false;
      
      const dischargeDate = moment(customer.discharge_date, 'MM/DD/YYYY');
      return dischargeDate.isBetween(startDate, endDate, 'day', '[]'); // inclusive
    });
    
    console.log('Discharged customers in selected week:', dischargedCustomers.length);
    
    const totalDischarged = dischargedCustomers.length;
    
    const dischargeReasonCounts = {
      'Absent for Over 30 Days': 0,
      'Transferred to Assisted Living': 0,
      'Deceased': 0,
      'Event': 0,
      'Other': 0,
      'N/A': 0
    };
    
    dischargedCustomers.forEach(customer => {
      if (customer.discharge_reason) {
        const reasonText = CUSTOMER_DISCHARGE_REASON_TEXT[customer.discharge_reason];
        if (reasonText) {
          dischargeReasonCounts[reasonText]++;
        } else {
          dischargeReasonCounts['N/A']++;
        }
      } else {
        dischargeReasonCounts['N/A']++;
      }
    });
    
    console.log('Discharge reason counts:', dischargeReasonCounts);
    
    const labels = Object.keys(dischargeReasonCounts);
    const data = Object.values(dischargeReasonCounts);
    const percentages = data.map(count => totalDischarged > 0 ? Math.round((count / totalDischarged) * 100) : 0);
    
    console.log('Labels:', labels, 'Data:', data, 'Percentages:', percentages);
    
    // Generate colors for each discharge reason
    const colors = [
      'rgb(255, 99, 132)',   // Red for Absent for Over 30 Days
      'rgb(54, 162, 235)',   // Blue for Transferred to Assisted Living
      'rgb(255, 205, 86)',   // Yellow for Deceased
      'rgb(75, 192, 192)',   // Teal for Event
      'rgb(153, 102, 255)',  // Purple for Other
      'rgb(201, 203, 207)'   // Gray for N/A
    ];
    
    const dischargeReasonsData = {
      labels,
      datasets: [{
        data,
        backgroundColor: colors,
        borderColor: colors.map(color => color.replace('rgb', 'rgba').replace(')', ', 0.8)')),
        borderWidth: 2,
        hoverOffset: 4
      }],
      percentages,
      totalDischarged
    };
    
    console.log('Setting dischargeReasonsData:', dischargeReasonsData);
    setDischargeReasonsData(dischargeReasonsData);
  };

  // Handle week selection change
  const handleWeekChange = (event) => {
    const newWeek = event.target.value;
    setSelectedWeek(newWeek);
    generateMemberTrendData(customers, newWeek);
    generateAttendanceTrendData(newWeek);
    generatePaySourceData(customers);
    generateNewAdmissionsData(customers, selectedMonth);
    generateDischargeReasonsData(customers, newWeek);
  };

  // Handle month selection change
  const handleMonthChange = (event) => {
    const newMonth = event.target.value;
    setSelectedMonth(newMonth);
    generateNewAdmissionsData(customers, newMonth);
  };

  // Handle discharge week selection change
  const handleDischargeWeekChange = (event) => {
    const newWeek = event.target.value;
    setSelectedDischargeWeek(newWeek);
    generateDischargeReasonsData(customers, newWeek);
  };

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">Dashboard</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Admin View
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Admin View</h4>
        </div>
      </div>

      {/* First Section - No border */}
      <div className="mb-4 admin-view-container">
        <Row>
          {/* Main Content - Full Width */}
          <Col md={12}>
            {/* First Row - Stats Card */}
            <Row className="mb-4">
              <Col md={12}>
                <Card className="admin-view-card">
                  <Card.Body>
                    <Row>
                      {/* Total Members */}
                      <Col md={3} className="text-center">
                        <div className="admin-view-stats-section">
                          <small className="mb-1 d-block admin-view-stats-label">Total Members</small>
                          <h3 className="text-primary">{statsData.totalMembers}</h3>
                          <small className="text-success">
                            +{statsData.totalMembersIncreaseRate}% from last month
                          </small>
                        </div>
                      </Col>
                      {/* Today's Attendance */}
                      <Col md={3} className="text-center">
                        <div className="admin-view-stats-section">
                          <small className="mb-1 d-block admin-view-stats-label">Today's Attendance</small>
                          <h3 className="text-success">{statsData.todayAttendance}</h3>
                          <small className={statsData.todayAttendanceTrend === 'increase' ? 'text-success' : 'text-danger'}>
                            {statsData.todayAttendanceTrend === 'increase' ? '↗' : '↘'} {statsData.todayAttendanceChangeRate.toFixed(1)}% {statsData.todayAttendanceTrend} from yesterday
                          </small>
                        </div>
                      </Col>
                      {/* New Members This Month */}
                      <Col md={3} className="text-center">
                        <div className="admin-view-stats-section">
                          <small className="mb-1 d-block admin-view-stats-label">New Members This Month</small>
                          <h3 className="text-info">{statsData.newMembersThisMonth}</h3>
                          <small className={statsData.newMembersTrend === 'increase' ? 'text-success' : 'text-danger'}>
                            {statsData.newMembersTrend === 'increase' ? '↗' : '↘'} {statsData.newMembersChangeRate.toFixed(1)}% {statsData.newMembersTrend} from last month
                          </small>
                        </div>
                      </Col>
                      {/* Member Discharges This Month */}
                      <Col md={3} className="text-center">
                        <div>
                          <small className="mb-1 d-block admin-view-stats-label">Member Discharges This Month</small>
                          <h3 className="text-warning">{statsData.memberDischargesThisMonth}</h3>
                          <small className={statsData.dischargesTrend === 'increase' ? 'text-danger' : 'text-success'}>
                            {statsData.dischargesTrend === 'increase' ? '↗' : '↘'} {statsData.dischargesChangeRate.toFixed(1)}% {statsData.dischargesTrend} from last month
                          </small>
                        </div>
                      </Col>
                    </Row>
                  </Card.Body>
                </Card>
              </Col>
            </Row>

            {/* Second Row - Charts */}
            <Row>
              <Col md={6}>
                <Card className="admin-view-card">
                  <Card.Body>
                    <div className="admin-view-chart-header">
                      <h6 className="admin-view-chart-title">Total Members</h6>
                      <select 
                        value={selectedWeek} 
                        onChange={handleWeekChange}
                        className="form-select form-select-sm admin-view-week-selector"
                      >
                        {generateWeekOptions().map(option => (
                          <option key={option.value} value={option.value}>
                            {option.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="admin-view-chart-container">
                      <Line 
                        data={memberTrendData}
                        options={{
                          responsive: true,
                          maintainAspectRatio: false,
                          plugins: {
                            legend: {
                              display: false
                            },
                            tooltip: {
                              enabled: true
                            }
                          },
                          scales: {
                            y: {
                              min: 100,
                              max: 300,
                              ticks: {
                                stepSize: 40
                              }
                            }
                          },
                          elements: {
                            point: {
                              backgroundColor: 'rgb(75, 192, 192)',
                              borderColor: 'white',
                              borderWidth: 2
                            }
                          }
                        }}
                      />
                      <div className="admin-view-average-display">
                        Average: {memberTrendData.average || 0}
                      </div>
                    </div>
                  </Card.Body>
                </Card>
              </Col>
              <Col md={6}>
                <Card className="admin-view-card">
                  <Card.Body>
                    <div className="admin-view-chart-header">
                      <h6 className="admin-view-chart-title">Total Attendance</h6>
                      <select 
                        value={selectedWeek} 
                        onChange={handleWeekChange}
                        className="form-select form-select-sm admin-view-week-selector"
                      >
                        {generateWeekOptions().map(option => (
                          <option key={option.value} value={option.value}>
                            {option.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="admin-view-chart-container">
                      <Line 
                        data={attendanceTrendData}
                        options={{
                          responsive: true,
                          maintainAspectRatio: false,
                          plugins: {
                            legend: {
                              display: false
                            },
                            tooltip: {
                              enabled: true
                            }
                          },
                          scales: {
                            y: {
                              min: 100,
                              max: 300,
                              ticks: {
                                stepSize: 40
                              }
                            }
                          },
                          elements: {
                            point: {
                              backgroundColor: 'rgb(255, 99, 132)',
                              borderColor: 'white',
                              borderWidth: 2
                            }
                          }
                        }}
                      />
                      <div className="admin-view-average-display">
                        Average: {attendanceTrendData.average || 0}
                      </div>
                    </div>
                  </Card.Body>
                </Card>
              </Col>
            </Row>
          </Col>

        </Row>
      </div>

      {/* Second Section - No border */}
      <div>
        <Row>
          <Col md={4}>
            <Card className="admin-view-card">
              <Card.Body>
                <h6 className="mb-3">Pay Source</h6>
                <div className="admin-view-chart-container">
                  <Doughnut 
                    data={paySourceData}
                    options={{
                      responsive: true,
                      maintainAspectRatio: false,
                      layout: {
                        padding: {
                          top: 40,
                          bottom: 40,
                          left: 40,
                          right: 40
                        }
                      },
                      plugins: {
                        legend: {
                          position: 'bottom',
                          labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                              size: 10
                            },
                            generateLabels: (chart) => {
                              const data = chart.data;
                              if (data.labels.length && data.datasets.length) {
                                return data.labels.map((label, i) => {
                                  const dataset = data.datasets[0];
                                  const value = dataset.data[i];
                                  return {
                                    text: `${label}: ${value}`,
                                    fillStyle: dataset.backgroundColor[i],
                                    strokeStyle: dataset.borderColor[i],
                                    lineWidth: 0,
                                    pointStyle: 'circle',
                                    hidden: false,
                                    index: i
                                  };
                                });
                              }
                              return [];
                            }
                          },
                          align: 'center',
                          maxHeight: 80
                        },
                        tooltip: {
                          enabled: false
                        }
                      }
                    }}
                    plugins={[{
                      afterDraw: (chart) => {
                        const ctx = chart.ctx;
                        console.log('AfterDraw plugin called', chart.data);
                        console.log('Chart datasets:', chart.data.datasets);
                        console.log('First dataset:', chart.data.datasets[0]);
                        console.log('First dataset data:', chart.data.datasets[0]?.data);
                        
                        const centerX = chart.chartArea.left + (chart.chartArea.right - chart.chartArea.left) / 2;
                        const centerY = chart.chartArea.top + (chart.chartArea.bottom - chart.chartArea.top) / 2;
                        const radius = Math.min(chart.chartArea.right - chart.chartArea.left, chart.chartArea.bottom - chart.chartArea.top) / 2;
                        
                        console.log('Chart center:', centerX, centerY, 'radius:', radius);
                        
                        // Check if data exists
                        if (chart.data.datasets[0] && chart.data.datasets[0].data) {
                          const data = chart.data.datasets[0].data;
                          const labels = chart.data.labels;
                          const total = data.reduce((sum, val) => sum + val, 0);
                          const percentages = data.map(value => total > 0 ? Math.round((value / total) * 100) : 0);
                          
                          console.log('Data found:', data, 'Percentages:', percentages);
                          
                          // Store annotation positions to check for overlaps
                          const annotationPositions = [];
                          
                          data.forEach((value, index) => {
                            const percentage = percentages[index];
                            const label = labels[index];
                            console.log(`Segment ${index}:`, value, percentage, label);
                            
                            if (value > 0) {
                              const angle = chart.getDatasetMeta(0).data[index].startAngle + 
                                          (chart.getDatasetMeta(0).data[index].endAngle - chart.getDatasetMeta(0).data[index].startAngle) / 2;
                              
                              // Calculate points for the line - make it shorter
                              const innerX = centerX + Math.cos(angle) * (radius * 0.95);
                              const innerY = centerY + Math.sin(angle) * (radius * 0.95);
                              const outerX = centerX + Math.cos(angle) * (radius * 1.05);
                              const outerY = centerY + Math.sin(angle) * (radius * 1.05);
                              
                              console.log(`Drawing line for segment ${index}:`, innerX, innerY, outerX, outerY);
                              
                              // Draw the line - make it thinner and lighter
                              ctx.save();
                              ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
                              ctx.lineWidth = 0.5;
                              ctx.beginPath();
                              ctx.moveTo(innerX, innerY);
                              ctx.lineTo(outerX, outerY);
                              ctx.stroke();
                              
                              // Draw the text with better positioning and include label
                              ctx.textAlign = angle > Math.PI/2 && angle < 3*Math.PI/2 ? 'right' : 'left';
                              ctx.textBaseline = 'middle';
                              ctx.font = 'bold 10px Arial';
                              ctx.fillStyle = '#333';
                              
                              // Calculate text position with better bounds checking
                              let textX = outerX + (angle > Math.PI/2 && angle < 3*Math.PI/2 ? -6 : 6);
                              let textY = outerY;
                              
                              // Ensure text stays within chart bounds
                              const textWidth = ctx.measureText(`${label}: ${value} (${percentage}%)`).width;
                              const padding = 15;
                              
                              // Adjust horizontal position if text would go outside chart
                              if (angle > Math.PI/2 && angle < 3*Math.PI/2) {
                                // Left side - check if text would go outside left edge
                                if (textX - textWidth < chart.chartArea.left + padding) {
                                  textX = chart.chartArea.left + padding + textWidth;
                                }
                              } else {
                                // Right side - check if text would go outside right edge
                                if (textX + textWidth > chart.chartArea.right - padding) {
                                  textX = chart.chartArea.right - padding - textWidth;
                                }
                              }
                              
                              // Adjust vertical position if text would go outside top/bottom
                              if (textY < chart.chartArea.top + padding) {
                                textY = chart.chartArea.top + padding;
                              } else if (textY > chart.chartArea.bottom - padding) {
                                textY = chart.chartArea.bottom - padding;
                              }
                              
                              // Check for overlaps with existing annotations
                              const textHeight = 12; // Approximate text height
                              const minDistance = 3; // Minimum distance between annotations
                              
                              let adjusted = false;
                              let attempts = 0;
                              const maxAttempts = 10;
                              
                              while (attempts < maxAttempts) {
                                let hasOverlap = false;
                                
                                for (const existingPos of annotationPositions) {
                                  const distanceX = Math.abs(textX - existingPos.x);
                                  const distanceY = Math.abs(textY - existingPos.y);
                                  
                                  // Check if annotations overlap
                                  if (distanceX < (textWidth + existingPos.width) / 2 + minDistance &&
                                      distanceY < (textHeight + existingPos.height) / 2 + minDistance) {
                                    hasOverlap = true;
                                    break;
                                  }
                                }
                                
                                if (!hasOverlap) {
                                  break;
                                }
                                
                                // Move the annotation to avoid overlap
                                const offset = (attempts + 1) * 10;
                                if (angle > Math.PI/2 && angle < 3*Math.PI/2) {
                                  // Left side - move further left
                                  textX -= offset;
                                } else {
                                  // Right side - move further right
                                  textX += offset;
                                }
                                
                                // Also adjust vertically if needed
                                if (angle > 0 && angle < Math.PI) {
                                  // Top half - move up
                                  textY -= offset * 0.5;
                                } else {
                                  // Bottom half - move down
                                  textY += offset * 0.5;
                                }
                                
                                attempts++;
                              }
                              
                              // Store this annotation position for future overlap checks
                              annotationPositions.push({
                                x: textX,
                                y: textY,
                                width: textWidth,
                                height: textHeight
                              });
                              
                              // Draw label with number and percentage
                              ctx.fillText(`${label}: ${value} (${percentage}%)`, textX, textY);
                              ctx.restore();
                            }
                          });
                        } else {
                          console.log('No data found - datasets[0]:', chart.data.datasets[0]);
                          console.log('No data found - datasets[0].data:', chart.data.datasets[0]?.data);
                        }
                      }
                    }]}
                  />
                  <div className="admin-view-donut-stats">
                    <div className="text-center">
                      <div className="h4 text-primary">{paySourceData.totalActive || 0}</div>
                    </div>
                  </div>
                </div>
              </Card.Body>
            </Card>
          </Col>
          <Col md={4}>
            <Card className="admin-view-card">
              <Card.Body>
                <div className="admin-view-chart-header">
                  <h6 className="admin-view-chart-title">New Admissions</h6>
                  <select 
                    value={selectedMonth} 
                    onChange={handleMonthChange}
                    className="form-select form-select-sm admin-view-week-selector"
                  >
                    {generateMonthOptions().map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="admin-view-chart-container-flexible">
                  <Doughnut 
                    data={newAdmissionsData}
                    options={{
                      responsive: true,
                      maintainAspectRatio: false,
                      layout: {
                        padding: {
                          top: 30,
                          bottom: 30,
                          left: 30,
                          right: 30
                        }
                      },
                      plugins: {
                        legend: {
                          position: 'bottom',
                          labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                              size: 10
                            },
                            generateLabels: (chart) => {
                              const data = chart.data;
                              if (data.labels.length && data.datasets.length) {
                                return data.labels.map((label, i) => {
                                  const dataset = data.datasets[0];
                                  const value = dataset.data[i];
                                  return {
                                    text: `${label}: ${value}`,
                                    fillStyle: dataset.backgroundColor[i],
                                    strokeStyle: dataset.borderColor[i],
                                    lineWidth: 0,
                                    pointStyle: 'circle',
                                    hidden: false,
                                    index: i
                                  };
                                });
                              }
                              return [];
                            }
                          },
                          align: 'center'
                        },
                        tooltip: {
                          enabled: false
                        }
                      }
                    }}
                    plugins={[{
                      afterDraw: (chart) => {
                        const ctx = chart.ctx;
                        console.log('AfterDraw plugin called for New Admissions', chart.data);
                        console.log('Chart datasets:', chart.data.datasets);
                        console.log('First dataset:', chart.data.datasets[0]);
                        console.log('First dataset data:', chart.data.datasets[0]?.data);
                        
                        const centerX = chart.chartArea.left + (chart.chartArea.right - chart.chartArea.left) / 2;
                        const centerY = chart.chartArea.top + (chart.chartArea.bottom - chart.chartArea.top) / 2;
                        const radius = Math.min(chart.chartArea.right - chart.chartArea.left, chart.chartArea.bottom - chart.chartArea.top) / 2;
                        
                        console.log('Chart center:', centerX, centerY, 'radius:', radius);
                        
                        // Check if data exists
                        if (chart.data.datasets[0] && chart.data.datasets[0].data) {
                          const data = chart.data.datasets[0].data;
                          const labels = chart.data.labels;
                          const total = data.reduce((sum, val) => sum + val, 0);
                          const percentages = data.map(value => total > 0 ? Math.round((value / total) * 100) : 0);
                          
                          console.log('Data found:', data, 'Percentages:', percentages);
                          
                          // Store annotation positions to check for overlaps
                          const annotationPositions = [];
                          
                          data.forEach((value, index) => {
                            const percentage = percentages[index];
                            const label = labels[index];
                            console.log(`Segment ${index}:`, value, percentage, label);
                            
                            if (value > 0) {
                              const angle = chart.getDatasetMeta(0).data[index].startAngle + 
                                          (chart.getDatasetMeta(0).data[index].endAngle - chart.getDatasetMeta(0).data[index].startAngle) / 2;
                              
                              // Calculate points for the line - make it shorter
                              const innerX = centerX + Math.cos(angle) * (radius * 0.95);
                              const innerY = centerY + Math.sin(angle) * (radius * 0.95);
                              const outerX = centerX + Math.cos(angle) * (radius * 1.05);
                              const outerY = centerY + Math.sin(angle) * (radius * 1.05);
                              
                              console.log(`Drawing line for segment ${index}:`, innerX, innerY, outerX, outerY);
                              
                              // Draw the line - make it thinner and lighter
                              ctx.save();
                              ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
                              ctx.lineWidth = 0.5;
                              ctx.beginPath();
                              ctx.moveTo(innerX, innerY);
                              ctx.lineTo(outerX, outerY);
                              ctx.stroke();
                              
                              // Draw the text with better positioning and include label
                              ctx.textAlign = angle > Math.PI/2 && angle < 3*Math.PI/2 ? 'right' : 'left';
                              ctx.textBaseline = 'middle';
                              ctx.font = 'bold 10px Arial';
                              ctx.fillStyle = '#333';
                              
                              // Calculate text position with better bounds checking
                              let textX = outerX + (angle > Math.PI/2 && angle < 3*Math.PI/2 ? -6 : 6);
                              let textY = outerY;
                              
                              // Ensure text stays within chart bounds
                              const textWidth = ctx.measureText(`${label}: ${value} (${percentage}%)`).width;
                              const padding = 15;
                              
                              // Adjust horizontal position if text would go outside chart
                              if (angle > Math.PI/2 && angle < 3*Math.PI/2) {
                                // Left side - check if text would go outside left edge
                                if (textX - textWidth < chart.chartArea.left + padding) {
                                  textX = chart.chartArea.left + padding + textWidth;
                                }
                              } else {
                                // Right side - check if text would go outside right edge
                                if (textX + textWidth > chart.chartArea.right - padding) {
                                  textX = chart.chartArea.right - padding - textWidth;
                                }
                              }
                              
                              // Adjust vertical position if text would go outside top/bottom
                              if (textY < chart.chartArea.top + padding) {
                                textY = chart.chartArea.top + padding;
                              } else if (textY > chart.chartArea.bottom - padding) {
                                textY = chart.chartArea.bottom - padding;
                              }
                              
                              // Check for overlaps with existing annotations
                              const textHeight = 12; // Approximate text height
                              const minDistance = 3; // Minimum distance between annotations
                              
                              let adjusted = false;
                              let attempts = 0;
                              const maxAttempts = 10;
                              
                              while (attempts < maxAttempts) {
                                let hasOverlap = false;
                                
                                for (const existingPos of annotationPositions) {
                                  const distanceX = Math.abs(textX - existingPos.x);
                                  const distanceY = Math.abs(textY - existingPos.y);
                                  
                                  // Check if annotations overlap
                                  if (distanceX < (textWidth + existingPos.width) / 2 + minDistance &&
                                      distanceY < (textHeight + existingPos.height) / 2 + minDistance) {
                                    hasOverlap = true;
                                    break;
                                  }
                                }
                                
                                if (!hasOverlap) {
                                  break;
                                }
                                
                                // Move the annotation to avoid overlap
                                const offset = (attempts + 1) * 10;
                                if (angle > Math.PI/2 && angle < 3*Math.PI/2) {
                                  // Left side - move further left
                                  textX -= offset;
                                } else {
                                  // Right side - move further right
                                  textX += offset;
                                }
                                
                                // Also adjust vertically if needed
                                if (angle > 0 && angle < Math.PI) {
                                  // Top half - move up
                                  textY -= offset * 0.5;
                                } else {
                                  // Bottom half - move down
                                  textY += offset * 0.5;
                                }
                                
                                attempts++;
                              }
                              
                              // Store this annotation position for future overlap checks
                              annotationPositions.push({
                                x: textX,
                                y: textY,
                                width: textWidth,
                                height: textHeight
                              });
                              
                              // Draw label with number and percentage
                              ctx.fillText(`${label}: ${value} (${percentage}%)`, textX, textY);
                              ctx.restore();
                            }
                          });
                        } else {
                          console.log('No data found - datasets[0]:', chart.data.datasets[0]);
                          console.log('No data found - datasets[0].data:', chart.data.datasets[0]?.data);
                        }
                      }
                    }]}
                  />
                  <div className="admin-view-donut-stats">
                    <div className="text-center">
                      <div className="h4 text-primary">{newAdmissionsData.totalInMonth || 0}</div>
                    </div>
                  </div>
                </div>
              </Card.Body>
            </Card>
          </Col>
          <Col md={4}>
            <Card className="admin-view-card">
              <Card.Body>
                <div className="admin-view-chart-header">
                  <h6 className="admin-view-chart-title">Discharge Reasons</h6>
                  <select 
                    value={selectedDischargeWeek} 
                    onChange={handleDischargeWeekChange}
                    className="form-select form-select-sm admin-view-week-selector"
                  >
                    {generateWeekOptions().map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="admin-view-chart-container-flexible">
                  <Doughnut 
                    data={dischargeReasonsData}
                    options={{
                      responsive: true,
                      maintainAspectRatio: false,
                      layout: {
                        padding: {
                          top: 30,
                          bottom: 30,
                          left: 30,
                          right: 30
                        }
                      },
                      plugins: {
                        legend: {
                          position: 'bottom',
                          labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                              size: 10
                            },
                            generateLabels: (chart) => {
                              const data = chart.data;
                              if (data.labels.length && data.datasets.length) {
                                return data.labels.map((label, i) => {
                                  const dataset = data.datasets[0];
                                  const value = dataset.data[i];
                                  return {
                                    text: `${label}: ${value}`,
                                    fillStyle: dataset.backgroundColor[i],
                                    strokeStyle: dataset.borderColor[i],
                                    lineWidth: 0,
                                    pointStyle: 'circle',
                                    hidden: false,
                                    index: i
                                  };
                                });
                              }
                              return [];
                            }
                          },
                          align: 'center'
                        },
                        tooltip: {
                          enabled: false
                        }
                      }
                    }}
                  />
                  <div className="admin-view-donut-stats">
                    <div className="text-center">
                      <div className="h4 text-primary">{dischargeReasonsData.totalDischarged || 0}</div>
                    </div>
                  </div>
                </div>
              </Card.Body>
            </Card>
          </Col>
        </Row>
      </div>
    </>
  );
};

export default AdminView; 