"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { Loader2, Search } from "lucide-react";
import { toast } from "sonner";
import { apiClient } from "@/lib/api/client";
import { EDataTable, EDataTableColumn } from "@/components/common/EDataTable";
import {
  ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid,
  Tooltip, Legend, ResponsiveContainer,
} from "recharts";

// TASK:ERP-022 — KPI 일별 생산량 (COMPANY_16)
type Row = {
  prod_date: string;
  production_qty: number;
  defect_qty: number;
  work_hours: number;
  remark?: string | null;
};

function defaultRange() {
  const now = new Date();
  const y = now.getFullYear();
  const m = now.getMonth();
  const start = new Date(y, m, 1);
  const end = new Date(y, m + 1, 0);
  const fmt = (d: Date) => d.toISOString().slice(0, 10);
  return { from: fmt(start), to: fmt(end) };
}

export default function KpiDailyProductionPage() {
  const init = defaultRange();
  const [from, setFrom] = useState(init.from);
  const [to, setTo] = useState(init.to);
  const [rows, setRows] = useState<Row[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchData = useCallback(async () => {
    if (!from || !to) {
      toast.error("기간을 입력해주세요");
      return;
    }
    setLoading(true);
    try {
      const res = await apiClient.get(`/kpi/daily-production`, { params: { from, to } });
      const data: Row[] = res.data?.data || [];
      setRows(data);
    } catch (err: any) {
      toast.error(err?.response?.data?.message || "조회 실패");
    } finally {
      setLoading(false);
    }
  }, [from, to]);

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const chartData = useMemo(() => {
    return rows.map((r) => {
      const d = new Date(r.prod_date);
      const label = `${d.getMonth() + 1}/${d.getDate()}`;
      const hourly = Number(r.work_hours) > 0
        ? Number(r.production_qty) / Number(r.work_hours)
        : 0;
      return {
        label,
        production_qty: Number(r.production_qty) || 0,
        work_hours: Number(r.work_hours) || 0,
        hourly: Math.round(hourly * 100) / 100,
      };
    });
  }, [rows]);

  const summary = useMemo(() => {
    const totalQty = rows.reduce((a, r) => a + (Number(r.production_qty) || 0), 0);
    const totalHours = rows.reduce((a, r) => a + (Number(r.work_hours) || 0), 0);
    const totalDefect = rows.reduce((a, r) => a + (Number(r.defect_qty) || 0), 0);
    const hourly = totalHours > 0 ? totalQty / totalHours : 0;
    return {
      totalQty,
      totalHours: Math.round(totalHours * 100) / 100,
      totalDefect,
      hourly: Math.round(hourly * 100) / 100,
    };
  }, [rows]);

  const columns = useMemo<EDataTableColumn[]>(() => [
    { key: "prod_date", label: "일자", width: "120px",
      render: (_v, row) => row.prod_date ? String(row.prod_date).slice(0, 10) : "-" },
    { key: "production_qty", label: "생산수량", width: "120px", align: "right", formatNumber: true },
    { key: "defect_qty", label: "불량수량", width: "100px", align: "right", formatNumber: true },
    { key: "work_hours", label: "작업시간(h)", width: "120px", align: "right",
      render: (_v, row) => Number(row.work_hours || 0).toFixed(2) },
    { key: "hourly", label: "시간당 생산량", width: "140px", align: "right",
      render: (_v, row) => {
        const wh = Number(row.work_hours) || 0;
        if (wh === 0) return "-";
        const v = Number(row.production_qty) / wh;
        return v.toFixed(2);
      } },
  ], []);

  return (
    <div className="flex h-[calc(100vh-4rem)] flex-col gap-3 p-3 overflow-hidden">
      <div className="shrink-0 flex items-end gap-2 flex-wrap">
        <div className="flex flex-col gap-1">
          <Label className="text-xs text-muted-foreground">시작일</Label>
          <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className="h-9 w-40" />
        </div>
        <div className="flex flex-col gap-1">
          <Label className="text-xs text-muted-foreground">종료일</Label>
          <Input type="date" value={to} onChange={(e) => setTo(e.target.value)} className="h-9 w-40" />
        </div>
        <Button onClick={fetchData} disabled={loading} className="h-9">
          {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <><Search className="h-4 w-4 mr-1" />조회</>}
        </Button>
      </div>

      <div className="shrink-0 grid grid-cols-4 gap-3">
        <Card className="p-3">
          <div className="text-xs text-muted-foreground">총 생산수량</div>
          <div className="text-2xl font-bold mt-1">{summary.totalQty.toLocaleString()}</div>
        </Card>
        <Card className="p-3">
          <div className="text-xs text-muted-foreground">총 작업시간 (h)</div>
          <div className="text-2xl font-bold mt-1">{summary.totalHours.toLocaleString()}</div>
        </Card>
        <Card className="p-3">
          <div className="text-xs text-muted-foreground">총 불량수량</div>
          <div className="text-2xl font-bold mt-1">{summary.totalDefect.toLocaleString()}</div>
        </Card>
        <Card className="p-3 bg-primary/5 border-primary/20">
          <div className="text-xs text-muted-foreground">시간당 평균 생산량</div>
          <div className="text-2xl font-bold mt-1 text-primary">{summary.hourly.toLocaleString()}</div>
        </Card>
      </div>

      <Card className="shrink-0 p-3">
        <div className="text-sm font-semibold mb-2">일별 생산량 / 작업시간</div>
        <div style={{ width: "100%", height: 320 }}>
          <ResponsiveContainer>
            <ComposedChart data={chartData} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="label" tick={{ fontSize: 11 }} />
              <YAxis yAxisId="left" tick={{ fontSize: 11 }} />
              <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 11 }} />
              <Tooltip />
              <Legend wrapperStyle={{ fontSize: 12 }} />
              <Bar yAxisId="left" dataKey="production_qty" name="생산수량" fill="#3b82f6" radius={[4, 4, 0, 0]} />
              <Line yAxisId="right" type="monotone" dataKey="work_hours" name="작업시간(h)" stroke="#f97316" strokeWidth={2} dot={{ r: 3 }} />
            </ComposedChart>
          </ResponsiveContainer>
        </div>
      </Card>

      <div className="flex flex-1 min-h-0 flex-col overflow-hidden border rounded-lg bg-card">
        <EDataTable
          columns={columns}
          data={rows}
          loading={loading}
          emptyMessage="기간 내 데이터가 없어요"
          showPagination
          draggableColumns={false}
          rowKey={(r: any) => r.prod_date}
          columnOrderKey="c16-kpi-daily-production"
        />
      </div>
    </div>
  );
}
