import { useState, useMemo, useEffect, useCallback, CSSProperties } from 'react';
import { Card, Table, Tabs, Select, Button, Typography, message, DatePicker, Tag } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';
import { useAppContext } from '../store/AppContext';
import { ROUTES } from '../router/routes.constant';
import dayjs, { Dayjs } from 'dayjs';

type LoanStatus = 'ACTIVE' | 'RETURNED' | 'OVERDUE' | 'LOST';
type PaymentMethod = 'CASH' | 'CREDIT_CARD' | 'DEBIT_CARD' | 'ONLINE' | 'CHECK';

interface LoanResponse {
  id: string;
  member_id: string;
  book_copy_id: string;
  checkout_date: string;
  due_date: string;
  return_date: string | null;
  renewal_count: number;
  status: LoanStatus;
  checked_out_by_librarian_id: string | null;
  checked_in_by_librarian_id: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface PaymentResponse {
  id: string;
  member_id: string;
  fine_id: string | null;
  amount: number;
  payment_method: PaymentMethod;
  transaction_date: string;
  reference_number: string | null;
  processed_by_librarian_id: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

export default function MemberHistoryPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const { currentUser } = useAppContext();

  const [loans, setLoans] = useState<LoanResponse[]>([]);
  const [payments, setPayments] = useState<PaymentResponse[]>([]);
  const [activeTab, setActiveTab] = useState<string>('borrowing');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const [filterDateRange, setFilterDateRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [loansLoading, setLoansLoading] = useState<boolean>(false);
  const [paymentsLoading, setPaymentsLoading] = useState<boolean>(false);
  const [loansPagination, setLoansPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [paymentsPagination, setPaymentsPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  const loansOffset = useMemo(() => {
    return (loansPagination.current - 1) * loansPagination.pageSize;
  }, [loansPagination.current, loansPagination.pageSize]);

  const paymentsOffset = useMemo(() => {
    return (paymentsPagination.current - 1) * paymentsPagination.pageSize;
  }, [paymentsPagination.current, paymentsPagination.pageSize]);

  const fetchLoans = useCallback(async () => {
    if (!currentUser?.memberId) return;
    
    setLoansLoading(true);
    try {
      const queryParams: Record<string, string | number> = {
        member_id: currentUser.memberId,
        limit: 20,
        offset: loansOffset,
      };
      
      if (filterStatus) {
        queryParams.status = filterStatus;
      }

      const result = await request<LoanResponse[]>({
        method: 'GET',
        path: '/loans/',
        query: queryParams,
      });

      setLoans(result.data);
      setLoansPagination(prev => ({
        ...prev,
        total: result.data.length,
      }));
    } catch (error) {
      messageApi.error('Failed to load borrowing history');
    } finally {
      setLoansLoading(false);
    }
  }, [currentUser?.memberId, loansOffset, filterStatus, messageApi]);

  const fetchPayments = useCallback(async () => {
    if (!currentUser?.memberId) return;
    
    setPaymentsLoading(true);
    try {
      const result = await request<PaymentResponse[]>({
        method: 'GET',
        path: '/fines/payments',
        query: {
          member_id: currentUser.memberId,
          limit: 20,
          offset: paymentsOffset,
        },
      });

      setPayments(result.data);
      setPaymentsPagination(prev => ({
        ...prev,
        total: result.data.length,
      }));
    } catch (error) {
      messageApi.error('Failed to load payment history');
    } finally {
      setPaymentsLoading(false);
    }
  }, [currentUser?.memberId, paymentsOffset, messageApi]);

  useEffect(() => {
    if (activeTab === 'borrowing') {
      fetchLoans();
    }
  }, [activeTab, fetchLoans]);

  useEffect(() => {
    if (activeTab === 'payments') {
      fetchPayments();
    }
  }, [activeTab, fetchPayments]);

  const navigateToDashboard = useCallback(() => {
    navigate(ROUTES.DASHBOARD);
  }, [navigate]);

  const onTabChange = useCallback((key: string) => {
    setActiveTab(key);
  }, []);

  const onStatusFilterChange = useCallback((value: string) => {
    setFilterStatus(value);
    setLoansPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  const onDateRangeChange = useCallback((dates: [Dayjs, Dayjs] | null) => {
    setFilterDateRange(dates);
    setLoansPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  const onLoansPageChange = useCallback((page: number) => {
    setLoansPagination(prev => ({ ...prev, current: page }));
  }, []);

  const onPaymentsPageChange = useCallback((page: number) => {
    setPaymentsPagination(prev => ({ ...prev, current: page }));
  }, []);

  const getStatusColor = (status: LoanStatus): string => {
    switch (status) {
      case 'ACTIVE':
        return 'blue';
      case 'RETURNED':
        return 'green';
      case 'OVERDUE':
        return 'red';
      case 'LOST':
        return 'volcano';
      default:
        return 'default';
    }
  };

  const loansColumns = useMemo(() => [
    {
      title: 'Book Title',
      dataIndex: 'book_title',
      key: 'book_title',
      render: () => '-',
    },
    {
      title: 'Author',
      dataIndex: 'book_author',
      key: 'book_author',
      render: () => '-',
    },
    {
      title: 'Barcode',
      dataIndex: 'barcode',
      key: 'barcode',
      render: () => '-',
    },
    {
      title: 'Checkout Date',
      dataIndex: 'checkout_date',
      key: 'checkout_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: 'Due Date',
      dataIndex: 'due_date',
      key: 'due_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: 'Return Date',
      dataIndex: 'return_date',
      key: 'return_date',
      render: (date: string | null) => date ? dayjs(date).format('YYYY-MM-DD') : '-',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: LoanStatus) => (
        <Tag color={getStatusColor(status)}>{status}</Tag>
      ),
    },
    {
      title: 'Fines',
      dataIndex: 'fine_amount',
      key: 'fine_amount',
      render: () => '-',
    },
  ], []);

  const paymentsColumns = useMemo(() => [
    {
      title: 'Transaction ID',
      dataIndex: 'reference_number',
      key: 'reference_number',
      render: (ref: string | null) => ref || '-',
    },
    {
      title: 'Date',
      dataIndex: 'transaction_date',
      key: 'transaction_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `$${amount.toFixed(2)}`,
    },
    {
      title: 'Payment Method',
      dataIndex: 'payment_method',
      key: 'payment_method',
    },
    {
      title: 'Fine Covered',
      dataIndex: 'fine_id',
      key: 'fine_id',
      render: (fineId: string | null) => fineId || '-',
    },
    {
      title: 'Receipt',
      dataIndex: 'receipt_link',
      key: 'receipt_link',
      render: () => '-',
    },
  ], []);

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    width: '100%',
    padding: '24px',
    background: '#f5f5f5',
    display: 'flex',
    flexDirection: 'column',
  };

  const pageHeaderStyle: CSSProperties = {
    marginBottom: '24px',
    display: 'flex',
    flexDirection: 'column',
    gap: '4px',
  };

  const backButtonStyle: CSSProperties = {
    paddingLeft: '0',
    marginBottom: '8px',
  };

  const titleStyle: CSSProperties = {
    marginBottom: '0',
  };

  const cardStyle: CSSProperties = {
    borderRadius: '6px',
  };

  const filtersRowStyle: CSSProperties = {
    marginBottom: '16px',
    display: 'flex',
    flexDirection: 'row',
    gap: '16px',
    flexWrap: 'wrap',
  };

  const datePickerStyle: CSSProperties = {
    width: '280px',
  };

  const selectStyle: CSSProperties = {
    width: '160px',
  };

  const tabItems = [
    {
      key: 'borrowing',
      label: 'Borrowing History',
      children: (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <div style={filtersRowStyle}>
            <DatePicker.RangePicker
              value={filterDateRange}
              onChange={onDateRangeChange}
              placeholder={['Start Date', 'End Date']}
              allowClear
              style={datePickerStyle}
            />
            <Select
              value={filterStatus}
              onChange={onStatusFilterChange}
              placeholder="All Statuses"
              allowClear
              style={selectStyle}
              options={[
                { label: 'All', value: '' },
                { label: 'Active', value: 'ACTIVE' },
                { label: 'Returned', value: 'RETURNED' },
                { label: 'Overdue', value: 'OVERDUE' },
              ]}
            />
          </div>
          <Table
            columns={loansColumns}
            dataSource={loans}
            rowKey="id"
            loading={loansLoading}
            pagination={{
              current: loansPagination.current,
              pageSize: loansPagination.pageSize,
              total: loansPagination.total,
              onChange: onLoansPageChange,
            }}
          />
        </div>
      ),
    },
    {
      key: 'payments',
      label: 'Payment History',
      children: (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <Table
            columns={paymentsColumns}
            dataSource={payments}
            rowKey="id"
            loading={paymentsLoading}
            pagination={{
              current: paymentsPagination.current,
              pageSize: paymentsPagination.pageSize,
              total: paymentsPagination.total,
              onChange: onPaymentsPageChange,
            }}
          />
        </div>
      ),
    },
  ];

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <div style={pageHeaderStyle}>
        <Button
          type="link"
          icon={<ArrowLeftOutlined />}
          onClick={navigateToDashboard}
          style={backButtonStyle}
        >
          Back to Dashboard
        </Button>
        <Typography.Title level={2} style={titleStyle}>
          Borrowing History
        </Typography.Title>
        <Typography.Text type="secondary">
          View your complete borrowing and payment history
        </Typography.Text>
      </div>
      <Card style={cardStyle}>
        <Tabs
          activeKey={activeTab}
          onChange={onTabChange}
          items={tabItems}
        />
      </Card>
    </div>
  );
}