import { useState } from 'react';
import { Alert, Col, Form, Input, InputNumber, Modal, Progress, Row, Select, Space, Typography, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef } from '@ag-grid-community/core';
import dayjs from 'dayjs';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ReferenceLine,
} from 'recharts';
import PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import { trainingApi, AgentTrainingRow, AgentTrainingSaveReq, AgentTrainingSearchParam } from '@/api/training';
import { GRAY, RADIUS, SHADOW, COLOR_PRIMARY, COLOR_SUCCESS, COLOR_ERROR } from '@/theme/tokens';

const { Text } = Typography;

const COLUMNS: ColDef<AgentTrainingRow>[] = [
  { field: 'agentName',       headerName: '설계사',     width: 120, pinned: 'left' },
  { field: 'trainingName',    headerName: '교육명',     flex: 1 },
  { field: 'trainingType',    headerName: '교육유형',   width: 120 },
  { field: 'completedHours',  headerName: '이수시간(H)', width: 120, type: 'numericColumn' },
  { field: 'trainingDate',    headerName: '교육일',     width: 120 },
  { field: 'provider',        headerName: '교육기관',   width: 140 },
  { field: 'year',            headerName: '연도',       width: 90 },
  { field: 'status',          headerName: '상태',       width: 90 },
];

const REQUIRED_HOURS = 12; // 의무 12시간/년

export default function AgentTrainings() {
  const qc = useQueryClient();
  const currentYear = dayjs().year();
  const [params, setParams] = useState<AgentTrainingSearchParam>({ year: currentYear, pageSize: 200 });
  const [selectedAgentId, setSelectedAgentId] = useState<number | null>(null);
  const [selectedAgentName, setSelectedAgentName] = useState('');
  const [createOpen, setCreateOpen] = useState(false);
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['agent-trainings', params],
    queryFn: () => trainingApi.list(params),
    retry: false,
  });

  const { data: annualHours } = useQuery({
    queryKey: ['agent-trainings', 'annual', selectedAgentId, currentYear],
    queryFn: () => trainingApi.annualHours(selectedAgentId!, currentYear),
    enabled: !!selectedAgentId,
    retry: false,
  });

  const rows = data?.list ?? [];

  // 설계사별 연간 합계 계산 (클라이언트사이드)
  const agentHoursMap: Record<number, number> = {};
  rows.forEach((r) => {
    agentHoursMap[r.agentId] = (agentHoursMap[r.agentId] ?? 0) + r.completedHours;
  });

  const chartData = selectedAgentId && annualHours ? [
    { label: '이수', hours: annualHours.completedHours },
    { label: '의무', hours: annualHours.requiredHours },
  ] : [];

  const handleCreate = async () => {
    const values = await form.validateFields() as AgentTrainingSaveReq;
    try {
      await trainingApi.create(values);
      message.success('교육 이수 등록 완료');
      qc.invalidateQueries({ queryKey: ['agent-trainings'] });
      setCreateOpen(false);
      form.resetFields();
    } catch { /* handled */ }
  };

  const satisfactionRate = annualHours
    ? Math.min(100, Math.round((annualHours.completedHours / REQUIRED_HOURS) * 100))
    : 0;

  return (
    <PageContainer
      title="보수교육 관리"
      description="설계사 의무교육 이수 시간 관리 (의무: 12시간/년)"
      extra={
        <PermissionButton menuCode="AGENT_TRAININGS" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
          + 교육 이수 등록
        </PermissionButton>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/agent-trainings 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'agentName',   label: '설계사명', span: 6 },
          { type: 'text', name: 'year',         label: '연도',     span: 6 },
          { type: 'code', name: 'trainingType', label: '교육유형', groupCode: 'TRAINING_TYPE', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as AgentTrainingSearchParam, pageSize: 200 })}
        onReset={() => setParams({ year: currentYear, pageSize: 200 })}
      />

      <Row gutter={20} style={{ marginBottom: 16 }}>
        {/* 설계사 선택 → 연간 차트 */}
        <Col span={8}>
          <ProCard
            title={<Text style={{ fontSize: 14, fontWeight: 700 }}>설계사별 연간 이수 현황</Text>}
            style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm, height: 300 }}
          >
            <Select
              showSearch
              placeholder="설계사 선택"
              style={{ width: '100%', marginBottom: 12 }}
              options={Array.from(new Set(rows.map((r) => r.agentId))).map((id) => {
                const r = rows.find((x) => x.agentId === id)!;
                return { value: id, label: r.agentName };
              })}
              onChange={(val, opt) => {
                setSelectedAgentId(val);
                const single = Array.isArray(opt) ? opt[0] : opt;
                setSelectedAgentName(single?.label ?? '');
              }}
            />

            {annualHours ? (
              <Space direction="vertical" style={{ width: '100%' }}>
                <Progress
                  percent={satisfactionRate}
                  strokeColor={satisfactionRate >= 100 ? COLOR_SUCCESS : COLOR_ERROR}
                  format={() => `${annualHours.completedHours}H / ${REQUIRED_HOURS}H`}
                />
                <Text style={{ fontSize: 12, color: GRAY[500] }}>
                  {annualHours.satisfied ? '의무시간 충족' : `부족: ${REQUIRED_HOURS - annualHours.completedHours}시간`}
                </Text>
              </Space>
            ) : (
              <Text style={{ fontSize: 13, color: GRAY[400] }}>설계사를 선택하면 연간 현황이 표시됩니다</Text>
            )}
          </ProCard>
        </Col>

        {/* 미충족 설계사 현황 */}
        <Col span={16}>
          <ProCard
            title={<Text style={{ fontSize: 14, fontWeight: 700 }}>이수 현황 요약 ({currentYear}년)</Text>}
            style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm, height: 300 }}
          >
            <ResponsiveContainer width="100%" height={220}>
              <BarChart
                data={Object.entries(agentHoursMap).slice(0, 10).map(([id, hours]) => {
                  const agent = rows.find((r) => r.agentId === Number(id));
                  return { name: agent?.agentName ?? id, hours };
                })}
                margin={{ top: 8, right: 16, left: -8, bottom: 0 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke={GRAY[100]} vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 11, fill: GRAY[500] }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: GRAY[500] }} axisLine={false} tickLine={false} />
                <Tooltip formatter={(v) => [`${v}시간`, '이수시간']} />
                <ReferenceLine y={REQUIRED_HOURS} stroke={COLOR_ERROR} strokeDasharray="4 2" label={{ value: '의무 12H', fontSize: 11, fill: COLOR_ERROR }} />
                <Bar dataKey="hours" fill={COLOR_PRIMARY} radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </ProCard>
        </Col>
      </Row>

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<AgentTrainingRow>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={500}
          rowKey="trainingId"
        />
      </ProCard>

      <Modal title="교육 이수 등록" open={createOpen} onOk={handleCreate} onCancel={() => setCreateOpen(false)} okText="등록" cancelText="취소">
        <Form form={form} layout="vertical">
          <Form.Item name="agentId" label="설계사 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="trainingName" label="교육명" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="trainingType" label="교육유형" rules={[{ required: true }]}>
            <Input placeholder="MANDATORY / OPTIONAL" />
          </Form.Item>
          <Form.Item name="completedHours" label="이수시간(H)" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} step={0.5} />
          </Form.Item>
          <Form.Item name="trainingDate" label="교육일" rules={[{ required: true }]}>
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="provider" label="교육기관">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
