import { useState } from 'react';
import { Alert, Form, Input, Modal, Space, Tag, Typography, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef, RowClassParams } from '@ag-grid-community/core';
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 { licenseApi, AgentLicenseRow, AgentLicenseSaveReq, AgentLicenseSearchParam } from '@/api/license';
import { GRAY, RADIUS, SHADOW, COLOR_WARNING, COLOR_WARNING_BG, COLOR_WARNING_BORDER, COLOR_ERROR, COLOR_ERROR_BG } from '@/theme/tokens';

const { Text } = Typography;

const COLUMNS: ColDef<AgentLicenseRow>[] = [
  { field: 'agentName',    headerName: '설계사',   width: 120, pinned: 'left' },
  { field: 'licenseTypeName', headerName: '자격 유형', width: 120 },
  { field: 'licenseNo',    headerName: '자격증번호', width: 160 },
  { field: 'issuedAt',     headerName: '발급일',   width: 120 },
  { field: 'expiresAt',    headerName: '만료일',   width: 120 },
  { field: 'renewedAt',    headerName: '갱신일',   width: 120 },
  {
    field: 'daysUntilExpiry', headerName: '만료까지',  width: 110,
    cellRenderer: (p: { value?: number }) => {
      const d = p.value;
      if (d == null) return '-';
      const color = d <= 0 ? COLOR_ERROR : d <= 30 ? COLOR_WARNING : GRAY[600];
      return <span style={{ color, fontWeight: d != null && d <= 30 ? 700 : 400 }}>{d <= 0 ? '만료' : `D-${d}`}</span>;
    },
  },
  { field: 'status', headerName: '상태', width: 90 },
];

export default function AgentLicenses() {
  const qc = useQueryClient();
  const [params, setParams] = useState<AgentLicenseSearchParam>({ pageSize: 100 });
  const [createOpen, setCreateOpen] = useState(false);
  const [form] = Form.useForm();

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

  const { data: expiring = [] } = useQuery({
    queryKey: ['agent-licenses', 'expiring'],
    queryFn: () => licenseApi.expiring(30),
    retry: false,
  });

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

  const handleCreate = async () => {
    const values = await form.validateFields() as AgentLicenseSaveReq;
    try {
      await licenseApi.create(values);
      message.success('자격증 등록 완료');
      qc.invalidateQueries({ queryKey: ['agent-licenses'] });
      setCreateOpen(false);
      form.resetFields();
    } catch { /* handled */ }
  };

  const getRowStyle = (p: RowClassParams<AgentLicenseRow>): Record<string, string> | undefined => {
    const d = p.data?.daysUntilExpiry;
    if (d != null && d <= 0) return { background: COLOR_ERROR_BG };
    if (d != null && d <= 30) return { background: COLOR_WARNING_BG, borderLeft: `3px solid ${COLOR_WARNING_BORDER}` };
    return undefined;
  };

  return (
    <PageContainer
      title="자격증 관리"
      description="설계사 생보/손보/변액 자격증 관리"
      extra={
        <PermissionButton menuCode="AGENT_LICENSES" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
          + 자격증 등록
        </PermissionButton>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/agent-licenses 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      {/* 만료 임박 헤더 카드 */}
      {expiring.length > 0 && (
        <div style={{
          padding: '12px 20px',
          background: COLOR_WARNING_BG,
          border: `1px solid ${COLOR_WARNING_BORDER}`,
          borderRadius: RADIUS.md,
          marginBottom: 16,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <Tag color="warning" style={{ fontWeight: 700, fontSize: 13 }}>
            30일 내 만료 {expiring.length}건
          </Tag>
          <Text style={{ fontSize: 13, color: GRAY[700] }}>
            {expiring.slice(0, 3).map((e) => `${e.agentName} (${e.licenseTypeName})`).join(', ')}
            {expiring.length > 3 ? ` 외 ${expiring.length - 3}건` : ''}
          </Text>
        </div>
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'agentName',   label: '설계사명',   span: 6 },
          { type: 'code', name: 'licenseType', label: '자격 유형',  groupCode: 'LICENSE_TYPE', span: 6 },
          { type: 'code', name: 'status',      label: '상태',       groupCode: 'LICENSE_STATUS', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as AgentLicenseSearchParam, pageSize: 100 })}
        onReset={() => setParams({ pageSize: 100 })}
      />

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<AgentLicenseRow>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={600}
          rowKey="licenseId"
          getRowStyle={getRowStyle}
        />
      </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 }]}>
            <Input />
          </Form.Item>
          <Form.Item name="licenseType" label="자격 유형" rules={[{ required: true }]}>
            <Input placeholder="LIFE / NONLIFE / VARIABLE" />
          </Form.Item>
          <Form.Item name="licenseNo" label="자격증 번호" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="issuedAt" label="발급일" rules={[{ required: true }]}>
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="expiresAt" label="만료일" rules={[{ required: true }]}>
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
