import { useState, useEffect, useMemo } from 'react';
import { Dropdown } from 'primereact/dropdown';
import { Calendar } from 'primereact/calendar';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Chart } from 'primereact/chart';
import BasePageHeader from '@/core/components/BasePageHeader';
import { reportService } from '../report.service';
import { projectService } from '@/modules/project/project.service';
import { toArray } from '@/core/api/utils';

export default function ReportView() {
  const [projects, setProjects] = useState<{ id: number; name: string }[]>([]);
  const [projectId, setProjectId] = useState<number | null>(null);
  const [dateFrom, setDateFrom] = useState<Date | null>(null);
  const [dateTo, setDateTo] = useState<Date | null>(null);
  const [groupBy, setGroupBy] = useState('project');
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const groupByOptions = [
    { label: '프로젝트', value: 'project' },
    { label: 'WBS', value: 'wbs' },
    { label: '사용자', value: 'user' },
    { label: '월별', value: 'month' },
  ];

  useEffect(() => {
    projectService.getAll()
      .then(({ data }) => setProjects(toArray<{ id: number; name: string }>(data)))
      .catch(() => setProjects([]));
  }, []);

  function search() {
    setLoading(true);
    const params: Record<string, unknown> = { groupBy };
    if (projectId) params.projectId = projectId;
    if (dateFrom) params.from = dateFrom.toISOString().slice(0, 10);
    if (dateTo) params.to = dateTo.toISOString().slice(0, 10);

    reportService.getProjectHours(params)
      .then(({ data }) => setData(toArray<Record<string, unknown>>(data)))
      .catch(() => setData([]))
      .finally(() => setLoading(false));
  }

  function exportExcel() {
    const params: Record<string, unknown> = { groupBy };
    if (projectId) params.projectId = projectId;
    if (dateFrom) params.from = dateFrom.toISOString().slice(0, 10);
    if (dateTo) params.to = dateTo.toISOString().slice(0, 10);

    reportService.exportProjectHours(params).then(({ data: blob }) => {
      const url = URL.createObjectURL(blob as Blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'report.xlsx';
      a.click();
      URL.revokeObjectURL(url);
    });
  }

  const chartData = useMemo(() => ({
    labels: data.map((d) => (d.label ?? d.name ?? '') as string),
    datasets: [{
      label: '시수',
      backgroundColor: 'var(--p-primary-color)',
      data: data.map((d) => (d.totalHours ?? d.hours ?? 0) as number),
    }],
  }), [data]);

  const chartOptions = useMemo(() => ({
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: { y: { beginAtZero: true } },
  }), []);

  return (
    <div>
      <BasePageHeader title="리포트" />

      <Card style={{ marginBottom: '1rem' }}>
        <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
          <div className="form-field">
            <label className="form-field__label">프로젝트</label>
            <Dropdown value={projectId} options={projects.map((p) => ({ label: p.name, value: p.id }))} onChange={(e) => setProjectId(e.value)} placeholder="전체" showClear />
          </div>
          <div className="form-field">
            <label className="form-field__label">시작일</label>
            <Calendar value={dateFrom} onChange={(e) => setDateFrom(e.value as Date)} dateFormat="yy-mm-dd" />
          </div>
          <div className="form-field">
            <label className="form-field__label">종료일</label>
            <Calendar value={dateTo} onChange={(e) => setDateTo(e.value as Date)} dateFormat="yy-mm-dd" />
          </div>
          <div className="form-field">
            <label className="form-field__label">그룹</label>
            <Dropdown value={groupBy} options={groupByOptions} onChange={(e) => setGroupBy(e.value)} />
          </div>
          <Button label="조회" icon="pi pi-search" onClick={search} loading={loading} />
          <Button label="Excel" icon="pi pi-file-excel" severity="success" outlined onClick={exportExcel} disabled={data.length === 0} />
        </div>
      </Card>

      {data.length > 0 && (
        <>
          <Card style={{ marginBottom: '1rem' }}>
            <div style={{ height: '300px' }}>
              <Chart type="bar" data={chartData} options={chartOptions} />
            </div>
          </Card>

          <DataTable value={data} size="small" stripedRows showGridlines paginator rows={20}>
            <Column field="label" header="구분" sortable body={(row) => row.label ?? row.name ?? '-'} />
            <Column field="totalHours" header="총 시수" sortable body={(row) => `${row.totalHours ?? row.hours ?? 0}h`} />
            <Column field="userCount" header="인원" sortable />
          </DataTable>
        </>
      )}
    </div>
  );
}
