import * as icon from '@mdi/js';
import Head from 'next/head'
import React, { useState, useEffect, useMemo } from 'react'
import axios from 'axios';
import type { ReactElement } from 'react'
import LayoutAuthenticated from '../layouts/Authenticated'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import CardBox from '../components/CardBox'
import BaseButton from '../components/BaseButton'
import { getPageTitle } from '../config'
import { useAppSelector } from '../stores/hooks';
import PTOStats from '../components/PTOStats'
import moment from 'moment'
import Link from 'next/link'
import StaffOffList from '../components/StaffOffList'
import Search from '../components/Search'
import { mdiPlusBox, mdiHospitalBox, mdiAlertDecagram } from '@mdi/js'
import CardBoxModal from '../components/CardBoxModal'

const Dashboard = () => {
  const { currentUser } = useAppSelector((state) => state.auth)
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear())
  const [summary, setSummary] = useState(null)
  const [approvals, setApprovals] = useState([])
  const [loading, setLoading] = useState(true)
  const [greeting, setGreeting] = useState('Hello')
  
  const [isReviewModalActive, setIsReviewModalActive] = useState(false)
  const [selectedTask, setSelectedTask] = useState(null)

  const canSeeApprovals = useMemo(() => {
    return currentUser?.app_role_permissions?.some(p => p.name === 'READ_APPROVAL_TASKS') || 
           currentUser?.custom_permissions?.some(p => p.name === 'READ_APPROVAL_TASKS');
  }, [currentUser]);

  const fetchDashboardData = async () => {
    setLoading(true)
    try {
      // Fetch PTO Summary for selected year
      const summaryRes = await axios.get(`/yearly_leave_summaries`, {
        params: {
          filter: JSON.stringify({
            userId: currentUser?.id,
            calendar_year: selectedYear
          })
        }
      })
      setSummary(summaryRes.data.rows[0] || null)

      // Fetch Pending Approvals if authorized
      if (canSeeApprovals) {
        const approvalsRes = await axios.get(`/approval_tasks`, {
          params: {
            filter: JSON.stringify({
              state: 'open'
            })
          }
        })
        setApprovals(approvalsRes.data.rows)
      }

    } catch (error) {
      console.error('Error fetching dashboard data:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (currentUser) {
      fetchDashboardData()
    }
  }, [currentUser, selectedYear, canSeeApprovals])

  useEffect(() => {
    const hour = new Date().getHours()
    if (hour < 12) setGreeting('Good morning')
    else if (hour < 18) setGreeting('Good afternoon')
    else setGreeting('Good evening')
  }, [])

  const handleApprove = async (taskId) => {
    if (!taskId) return;
    try {
      await axios.put(`/approval_tasks/${taskId}/approve`);
      // Refresh data
      fetchDashboardData();
      if (isReviewModalActive) setIsReviewModalActive(false);
    } catch (error) {
      console.error('Error approving task:', error);
      alert('Failed to approve task');
    }
  };

  const handleReject = async (taskId) => {
    if (!taskId) return;
    try {
      await axios.put(`/approval_tasks/${taskId}/reject`);
      // Refresh data
      fetchDashboardData();
      if (isReviewModalActive) setIsReviewModalActive(false);
    } catch (error) {
      console.error('Error rejecting task:', error);
      alert('Failed to reject task');
    }
  };

  const handleReview = (task) => {
    setSelectedTask(task);
    setIsReviewModalActive(true);
  };

  const years = [selectedYear - 1, selectedYear, selectedYear + 1, selectedYear + 2]

  return (
    <>
      <Head>
        <title>{getPageTitle('Home')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton 
          icon={icon.mdiHome} 
          title={`${greeting}, ${currentUser?.firstName || 'User'}`} 
          main
        >
          <div className="flex items-center">
            <div className="mr-6">
               <Search />
            </div>
            <div className="flex items-center space-x-2">
                <span className="text-sm text-gray-500">Year:</span>
                <select
                value={selectedYear}
                onChange={(e) => setSelectedYear(parseInt(e.target.value))}
                className="pl-2 pr-10 py-1 border rounded dark:bg-dark-800 dark:border-dark-700 dark:text-white"
                >
                {years.map(y => (
                    <option key={y} value={y}>{y}</option>
                ))}
                </select>
            </div>
          </div>
        </SectionTitleLineWithButton>

        {/* PTO Summary Stats */}
        <PTOStats
          summary={summary || {
            pto_pending_days: 0,
            pto_scheduled_days: 0,
            pto_taken_days: 0,
            pto_available_days: 0,
            medical_taken_days: 0
          }}
        />

        {/* Action Buttons */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <CardBox className="flex flex-col items-center justify-center p-6 cursor-pointer hover:shadow-lg transition-shadow" >
                <BaseButton
                    href="/time_off_requests/time_off_requests-new"
                    icon={mdiPlusBox}
                    label="Request Time Off"
                    color="info"
                    className="w-full mb-2"
                    iconSize={24}
                />
                <p className="text-gray-500 text-sm text-center">Submit a standard PTO request.</p>
            </CardBox>

            <CardBox className="flex flex-col items-center justify-center p-6 cursor-pointer hover:shadow-lg transition-shadow">
                 <BaseButton
                    href="/time_off_requests/time_off_requests-new?leave_type=medical_leave"
                    icon={mdiHospitalBox}
                    label="Take Medical Day"
                    color="danger"
                    className="w-full mb-2"
                    iconSize={24}
                />
                <p className="text-gray-500 text-sm text-center">Report a sick day or medical leave.</p>
            </CardBox>

            <CardBox className="flex flex-col items-center justify-center p-6 cursor-pointer hover:shadow-lg transition-shadow">
                 <BaseButton
                    href="/time_off_requests/time_off_requests-new?leave_type=unplanned_pto"
                    icon={mdiAlertDecagram}
                    label="Take Unplanned PTO"
                    color="warning"
                    className="w-full mb-2"
                    iconSize={24}
                />
                <p className="text-gray-500 text-sm text-center">Log unplanned absence.</p>
            </CardBox>
        </div>

        {/* Action Items (Approvals) - Full Width - Only show if user has permissions */}
        {canSeeApprovals && (
          <CardBox className="mb-6" hasTable>
              <div className="p-4 border-b dark:border-dark-700 flex justify-between items-center">
              <h3 className="font-bold">Action Items (Pending Approvals)</h3>
              <Link href="/approval_tasks/approval_tasks-list" className="text-sm text-blue-500 hover:underline">
                  View All
              </Link>
              </div>
              <div className="overflow-x-auto">
              <table className="w-full text-sm text-left">
                  <thead>
                  <tr className="border-b dark:border-dark-700">
                      <th className="p-4">Requester</th>
                      <th className="p-4">Type</th>
                      <th className="p-4">Dates</th>
                      <th className="p-4">Actions</th>
                  </tr>
                  </thead>
                  <tbody>
                  {approvals.length > 0 ? (
                      approvals.map((task) => (
                      <tr key={task.id} className="border-b dark:border-dark-700">
                          <td className="p-4">{task.time_off_request?.requester?.firstName} {task.time_off_request?.requester?.lastName}</td>
                          <td className="p-4 capitalize">{task.time_off_request?.leave_type?.replace(/_/g, ' ')}</td>
                          <td className="p-4">
                          {moment(task.time_off_request?.starts_at).format('MMM D')} - {moment(task.time_off_request?.ends_at).format('MMM D')}
                          </td>
                          <td className="p-4 whitespace-nowrap flex space-x-2">
                          <BaseButton
                              color="info"
                              label="Review"
                              small
                              onClick={() => handleReview(task)}
                          />
                          <BaseButton
                              color="success"
                              label="Approve"
                              small
                              onClick={() => handleApprove(task.id)}
                          />
                          <BaseButton
                              color="danger"
                              label="Decline"
                              small
                              onClick={() => handleReject(task.id)}
                          />
                          </td>
                      </tr>
                      ))
                  ) : (
                      <tr>
                      <td colSpan={4} className="p-4 text-center text-gray-500">No pending approvals</td>
                      </tr>
                  )}
                  </tbody>
              </table>
              </div>
          </CardBox>
        )}

        {/* Staff Off This Week - Full Width */}
        {currentUser && <StaffOffList />}

      </SectionMain>

      <CardBoxModal
        title="Review PTO Request"
        isActive={isReviewModalActive}
        onConfirm={() => handleApprove(selectedTask?.id)}
        onDecline={() => handleReject(selectedTask?.id)}
        onCancel={() => setIsReviewModalActive(false)}
        buttonColor="success"
        buttonLabel="Approve"
        declineButtonLabel="Decline"
        declineButtonColor="danger"
      >
        {selectedTask && (
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-2">
              <div className="font-bold text-gray-500">Requester:</div>
              <div>{selectedTask.time_off_request?.requester?.firstName} {selectedTask.time_off_request?.requester?.lastName}</div>
              
              <div className="font-bold text-gray-500">Leave Type:</div>
              <div className="capitalize">{selectedTask.time_off_request?.leave_type?.replace(/_/g, ' ')}</div>
              
              <div className="font-bold text-gray-500">Period:</div>
              <div>{moment(selectedTask.time_off_request?.starts_at).format('YYYY-MM-DD')} to {moment(selectedTask.time_off_request?.ends_at).format('YYYY-MM-DD')}</div>
              
              <div className="font-bold text-gray-500">Total Days:</div>
              <div>{selectedTask.time_off_request?.days}</div>
            </div>
            {selectedTask.time_off_request?.reason && (
              <div>
                <div className="font-bold text-gray-500 mb-1">Reason:</div>
                <div className="p-2 bg-gray-50 dark:bg-dark-800 rounded border dark:border-dark-700 italic">
                  {`"${selectedTask.time_off_request.reason}"`}
                </div>
              </div>
            )}
          </div>
        )}
      </CardBoxModal>
    </>
  )
}

Dashboard.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}

export default Dashboard;