'use client';

import React, { useEffect, useState } from 'react';
import { Card, Table, Tag, Typography, notification, Button } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { getPromotionHistory, PromotionHistoryRecord } from '../service';
import { displayDate } from '@/utills/helper';

const { Text } = Typography;

const statusColor = (status: string) => {
  switch (status?.toLowerCase()) {
    case 'completed':
    case 'success':
      return 'green';
    case 'pending':
      return 'orange';
    case 'failed':
    case 'error':
      return 'red';
    default:
      return 'default';
  }
};

const PromotionHistoryPage: React.FC = () => {
  const [records, setRecords] = useState<PromotionHistoryRecord[]>([]);
  const [loading, setLoading] = useState(false);

  const loadHistory = async () => {
    setLoading(true);
    try {
      const data = await getPromotionHistory();
      setRecords(data);
    } catch (err: any) {
      notification.error({
        message: 'Failed to load promotion history',
        description: err?.response?.data?.message ?? 'An unexpected error occurred.',
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadHistory();
  }, []);

  const columns = [
    {
      title: 'Effective Date',
      dataIndex: 'effectiveDate',
      key: 'effectiveDate',
      width: 140,
      render: (date: string) => displayDate(date),
      sorter: (a: PromotionHistoryRecord, b: PromotionHistoryRecord) =>
        new Date(a.effectiveDate).getTime() - new Date(b.effectiveDate).getTime(),
    },
    {
      title: 'Employee',
      dataIndex: 'employeeName',
      key: 'employeeName',
      width: 180,
      render: (name: string) => <Text strong>{name}</Text>,
    },
    {
      title: 'From Role',
      dataIndex: 'fromRoleName',
      key: 'fromRoleName',
      width: 160,
      render: (role: string) => <Tag>{role}</Tag>,
    },
    {
      title: 'To Role',
      dataIndex: 'toRoleName',
      key: 'toRoleName',
      width: 160,
      render: (role: string) => <Tag color="blue">{role}</Tag>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => (
        <Tag color={statusColor(status)}>{status}</Tag>
      ),
    },
    {
      title: 'Executed By',
      dataIndex: 'executedByName',
      key: 'executedByName',
      width: 180,
    },
    {
      title: 'Date Recorded',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 140,
      render: (date: string) => displayDate(date),
      sorter: (a: PromotionHistoryRecord, b: PromotionHistoryRecord) =>
        new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
    },
  ];

  return (
    <Card
      title="Promotion History"
      extra={
        <Button
          icon={<ReloadOutlined />}
          onClick={loadHistory}
          loading={loading}
        >
          Refresh
        </Button>
      }
    >
      <Table
        dataSource={records}
        columns={columns}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          pageSizeOptions: [10, 20, 50, 100],
          showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} entries`,
        }}
        scroll={{ x: 1000 }}
      />
    </Card>
  );
};

export default PromotionHistoryPage;
