import { useState, useEffect, useMemo } from 'react';
import { Card } from 'primereact/card';
import { Tag } from 'primereact/tag';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { ProgressSpinner } from 'primereact/progressspinner';
import { Chart } from 'primereact/chart';
import BasePageHeader from '@/core/components/BasePageHeader';
import { dashboardService } from '../dashboard.service';
import { TIMESHEET_STATUS } from '@/core/constants/app.constants';
import type { DashboardStat } from '../dashboard.types';
import './DashboardView.scss';

const defaultStats: DashboardStat[] = [
  { label: '금주 시수', value: 0, icon: 'pi pi-clock' },
  { label: '미제출 건수', value: 0, icon: 'pi pi-exclamation-triangle' },
  { label: '결재 대기', value: 0, icon: 'pi pi-check-square' },
  { label: '프로젝트 수', value: 0, icon: 'pi pi-briefcase' },
];

export default function DashboardView() {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<DashboardStat[]>(defaultStats);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const [weeklyHoursData, setWeeklyHoursData] = useState<any>(null);
  const [pendingApprovals, setPendingApprovals] = useState<Record<string, unknown>[]>([]);

  const chartOptions = useMemo(() => ({
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: {
      y: { beginAtZero: true, title: { display: true, text: '시간 (h)' } },
      x: { title: { display: true, text: '요일' } },
    },
  }), []);

  useEffect(() => {
    setLoading(true);
    dashboardService.getDashboard()
      .then(({ data }) => {
        const d = data as Record<string, unknown>;
        setStats(Array.isArray(d.stats) ? d.stats as DashboardStat[] : defaultStats);
        setPendingApprovals(Array.isArray(d.pendingApprovals) ? d.pendingApprovals as Record<string, unknown>[]
          : Array.isArray(d.recentTimesheets) ? d.recentTimesheets as Record<string, unknown>[] : []);
        setWeeklyHoursData({
          labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
          datasets: [{
            label: '시수',
            backgroundColor: '#3B82F6',
            data: Array.isArray(d.weeklyHours) ? d.weeklyHours : [0, 0, 0, 0, 0, 0],
          }],
        });
      })
      .catch(() => {
        setStats(defaultStats);
        setWeeklyHoursData({
          labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
          datasets: [{ label: '시수', backgroundColor: '#3B82F6', data: [0, 0, 0, 0, 0, 0] }],
        });
      })
      .finally(() => setLoading(false));
  }, []);

  function statusSeverity(status: string) {
    return (TIMESHEET_STATUS[status]?.severity ?? 'secondary') as 'success' | 'info' | 'warning' | 'danger' | 'secondary';
  }
  function statusLabel(status: string) {
    return TIMESHEET_STATUS[status]?.label ?? status;
  }

  if (loading) {
    return (
      <div>
        <BasePageHeader title="대시보드" subtitle="금주 시수 현황 및 결재 현황" />
        <div className="dashboard-view__loading"><ProgressSpinner /></div>
      </div>
    );
  }

  return (
    <div className="dashboard-view">
      <BasePageHeader title="대시보드" subtitle="금주 시수 현황 및 결재 현황" />

      <div className="dashboard-view__stats">
        {stats.map((stat, idx) => (
          <Card key={idx} className="dashboard-view__stat-card">
            <div className="stat-card">
              <div className="stat-card__icon"><i className={stat.icon} /></div>
              <div className="stat-card__info">
                <span className="stat-card__value">{stat.value}</span>
                <span className="stat-card__label">{stat.label}</span>
              </div>
              {stat.trend != null && (
                <div className={`stat-card__trend ${stat.trend > 0 ? 'stat-card__trend--up' : stat.trend < 0 ? 'stat-card__trend--down' : ''}`}>
                  <i className={stat.trend > 0 ? 'pi pi-arrow-up' : stat.trend < 0 ? 'pi pi-arrow-down' : 'pi pi-minus'} />
                  {Math.abs(stat.trend)}%
                </div>
              )}
            </div>
          </Card>
        ))}
      </div>

      <div className="dashboard-view__grid">
        <Card title="금주 시수 현황" className="dashboard-view__chart-card">
          <div className="dashboard-view__chart-wrapper">
            {weeklyHoursData && <Chart type="bar" data={weeklyHoursData as object} options={chartOptions} />}
          </div>
        </Card>

        <Card title="결재 대기 목록" className="dashboard-view__approvals-card">
          <DataTable value={pendingApprovals} rows={5} paginator={pendingApprovals.length > 5} size="small" stripedRows
            emptyMessage="결재 대기 건이 없습니다."
          >
            <Column field="requesterName" header="요청자" />
            <Column field="projectName" header="프로젝트" />
            <Column field="totalHours" header="시수" body={(row) => `${row.totalHours}h`} />
            <Column field="status" header="상태" body={(row) => <Tag value={statusLabel(row.status)} severity={statusSeverity(row.status)} />} />
          </DataTable>
        </Card>
      </div>
    </div>
  );
}
