import { useState } from 'react';
import { Alert, Button, Drawer, Form, Input, InputNumber, Modal, Space, Tabs, Tag, 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 PageContainer from '@/components/common/PageContainer';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import CodeBadge from '@/components/common/CodeBadge';
import ApprovalProgress from '@/components/biz/ApprovalProgress';
import {
  approvalApi,
  ApprovalLineRow, ApprovalRequestRow,
  ApprovalRequestSaveReq,
} from '@/api/approval';
import { GRAY, RADIUS, SHADOW, COLOR_SUCCESS, COLOR_ERROR, COLOR_PRIMARY } from '@/theme/tokens';

const { Text } = Typography;
const { TextArea } = Input;

const LINE_COLS: ColDef<ApprovalLineRow>[] = [
  { field: 'lineName',    headerName: '결재선명',   flex: 1 },
  { field: 'description', headerName: '설명',       flex: 1 },
  { field: 'stepCount',   headerName: '단계수',     width: 80, type: 'numericColumn' },
  { field: 'status',      headerName: '상태',       width: 90 },
  { field: 'createdAt',   headerName: '생성일',     width: 120 },
];

const REQ_COLS: ColDef<ApprovalRequestRow>[] = [
  { field: 'title',              headerName: '제목',     flex: 1 },
  { field: 'lineName',           headerName: '결재선',   width: 140 },
  { field: 'requesterName',      headerName: '요청자',   width: 110 },
  { field: 'currentApproverName', headerName: '현재 결재자', width: 130 },
  {
    headerName: '진행', width: 120,
    cellRenderer: (p: { data: ApprovalRequestRow }) => (
      <span style={{ fontSize: 12 }}>{p.data.currentStep} / {p.data.totalSteps} 단계</span>
    ),
  },
  {
    field: 'status', headerName: '상태', width: 100,
    cellRenderer: (p: { value: string }) => <CodeBadge groupCode="APPROVAL_STATUS" value={p.value} />,
  },
  { field: 'requestedAt', headerName: '요청일', width: 120 },
];

export default function Approvals() {
  const qc = useQueryClient();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedRequest, setSelectedRequest] = useState<ApprovalRequestRow | null>(null);
  const [approveComment, setApproveComment] = useState('');
  const [createReqOpen, setCreateReqOpen] = useState(false);
  const [form] = Form.useForm();

  const { data: linesData, isLoading: linesLoading, isError } = useQuery({
    queryKey: ['approval', 'lines'],
    queryFn: () => approvalApi.lines(),
    retry: false,
  });

  const { data: myReqData, isLoading: myReqLoading } = useQuery({
    queryKey: ['approval', 'mine'],
    queryFn: () => approvalApi.myRequests(),
    retry: false,
  });

  const { data: pendingData, isLoading: pendingLoading } = useQuery({
    queryKey: ['approval', 'pending'],
    queryFn: () => approvalApi.pendingRequests(),
    retry: false,
  });

  const lines = linesData?.list ?? [];
  const myRequests = myReqData?.list ?? [];
  const pendingRequests = pendingData?.list ?? [];

  const openDetail = async (req: ApprovalRequestRow) => {
    try {
      const detail = await approvalApi.requestDetail(req.requestId);
      setSelectedRequest(detail);
      setDrawerOpen(true);
    } catch { /* handled */ }
  };

  const handleAdvance = async (approved: boolean) => {
    if (!selectedRequest) return;
    try {
      await approvalApi.advance(selectedRequest.requestId, { approved, comment: approveComment });
      message.success(approved ? '승인 완료' : '반려 완료');
      qc.invalidateQueries({ queryKey: ['approval'] });
      setDrawerOpen(false);
      setApproveComment('');
    } catch { /* handled */ }
  };

  const handleCreateReq = async () => {
    const values = await form.validateFields() as ApprovalRequestSaveReq;
    try {
      await approvalApi.requestCreate(values);
      message.success('결재 요청 완료');
      qc.invalidateQueries({ queryKey: ['approval'] });
      setCreateReqOpen(false);
      form.resetFields();
    } catch { /* handled */ }
  };

  const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

  return (
    <PageContainer
      title="결재 관리"
      description="결재선 설정, 결재 요청, 결재 처리"
      extra={
        <PermissionButton menuCode="APPROVALS" permCode="CREATE" type="primary" onClick={() => setCreateReqOpen(true)}>
          + 결재 요청
        </PermissionButton>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/approvals 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <Tabs
        defaultActiveKey="lines"
        items={[
          {
            key: 'lines',
            label: `결재선 (${lines.length})`,
            children: (
              <ProCard style={cardStyle}>
                <DataGrid<ApprovalLineRow>
                  rows={lines}
                  columns={LINE_COLS}
                  loading={linesLoading}
                  height={480}
                  rowKey="lineId"
                />
              </ProCard>
            ),
          },
          {
            key: 'mine',
            label: `내 결재 요청 (${myRequests.length})`,
            children: (
              <ProCard style={cardStyle}>
                <DataGrid<ApprovalRequestRow>
                  rows={myRequests}
                  columns={REQ_COLS}
                  loading={myReqLoading}
                  height={480}
                  rowKey="requestId"
                />
              </ProCard>
            ),
          },
          {
            key: 'pending',
            label: (
              <span>
                결재 대기{' '}
                {pendingRequests.length > 0 && (
                  <Tag style={{ background: COLOR_ERROR, color: '#fff', border: 'none', marginLeft: 4, borderRadius: 99 }}>
                    {pendingRequests.length}
                  </Tag>
                )}
              </span>
            ),
            children: (
              <ProCard style={cardStyle}>
                <DataGrid<ApprovalRequestRow>
                  rows={pendingRequests}
                  columns={[
                    ...REQ_COLS,
                    {
                      headerName: '상세', width: 80, pinned: 'right',
                      cellRenderer: (p: { data: ApprovalRequestRow }) => (
                        <Button type="link" size="small" onClick={() => openDetail(p.data)}>상세</Button>
                      ),
                    },
                  ]}
                  loading={pendingLoading}
                  height={480}
                  rowKey="requestId"
                />
              </ProCard>
            ),
          },
        ]}
      />

      {/* 상세 Drawer */}
      <Drawer
        title={selectedRequest?.title}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={480}
        footer={
          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button danger onClick={() => handleAdvance(false)}>반려</Button>
            <Button type="primary" onClick={() => handleAdvance(true)}>승인</Button>
          </Space>
        }
      >
        {selectedRequest && (
          <Space direction="vertical" style={{ width: '100%' }} size={20}>
            <div>
              <Text style={{ fontSize: 12, color: GRAY[500] }}>요청자</Text>
              <div style={{ fontSize: 14, color: GRAY[800], marginTop: 4 }}>{selectedRequest.requesterName}</div>
            </div>
            <div>
              <Text style={{ fontSize: 12, color: GRAY[500] }}>내용</Text>
              <div style={{ fontSize: 14, color: GRAY[800], marginTop: 4, whiteSpace: 'pre-wrap' }}>{selectedRequest.content}</div>
            </div>

            {selectedRequest.steps && selectedRequest.steps.length > 0 && (
              <div>
                <Text style={{ fontSize: 12, color: GRAY[500], display: 'block', marginBottom: 8 }}>결재 진행 현황</Text>
                <ApprovalProgress
                  steps={selectedRequest.steps}
                  currentStep={selectedRequest.currentStep}
                />
              </div>
            )}

            <div>
              <Text style={{ fontSize: 12, color: GRAY[500], display: 'block', marginBottom: 4 }}>코멘트</Text>
              <TextArea
                rows={3}
                value={approveComment}
                onChange={(e) => setApproveComment(e.target.value)}
                placeholder="승인/반려 사유 (선택)"
              />
            </div>
          </Space>
        )}
      </Drawer>

      {/* 결재 요청 모달 */}
      <Modal
        title="결재 요청"
        open={createReqOpen}
        onOk={handleCreateReq}
        onCancel={() => setCreateReqOpen(false)}
        okText="요청"
        cancelText="취소"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="lineId" label="결재선 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="title" label="제목" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="content" label="내용" rules={[{ required: true }]}>
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
