import { useState, useMemo, useEffect, useCallback } from 'react';
import { Layout, Card, Statistic, Table, Button, Modal, Form, InputNumber, Select, Alert, Typography, message } 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';

type FineReason = 'OVERDUE' | 'DAMAGED' | 'LOST' | 'OTHER';
type FineStatus = 'UNPAID' | 'PARTIAL' | 'PAID' | 'WAIVED';
type PaymentMethod = 'CASH' | 'CREDIT_CARD' | 'DEBIT_CARD' | 'ONLINE' | 'CHECK' | 'OTHER';

interface FineResponse {
  id: string;
  member_id: string;
  loan_id: string | null;
  amount: number;
  amount_paid: number;
  reason: FineReason;
  description: string | null;
  status: FineStatus;
  assessed_date: string;
  due_date: string | null;
  waived_by: string | null;
  waived_date: string | null;
  waived_reason: string | null;
  created_at: string;
  updated_at: string;
}

interface PaymentDetailInFineResponse {
  id: string;
  payment_date: string;
  amount: number;
  payment_method: PaymentMethod;
  fine_id: string;
  receipt_number: string | null;
}

interface FineDetailResponse {
  id: string;
  member_id: string;
  loan_id: string | null;
  amount: number;
  amount_paid: number;
  reason: FineReason;
  description: string | null;
  status: FineStatus;
  assessed_date: string;
  due_date: string | null;
  waived_by: string | null;
  waived_date: string | null;
  waived_reason: string | null;
  created_at: string;
  updated_at: string;
  member: Record<string, unknown>;
  loan: Record<string, unknown> | null;
  waived_by_user: Record<string, unknown> | null;
  payments: PaymentDetailInFineResponse[];
}

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

  const [fines, setFines] = useState<FineResponse[]>([]);
  const [payments, setPayments] = useState<PaymentDetailInFineResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [paymentModalVisible, setPaymentModalVisible] = useState<boolean>(false);
  const [selectedFineId, setSelectedFineId] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<string | null>(null);

  const totalOutstandingBalance = useMemo(() => {
    return fines
      .filter(f => f.status === 'UNPAID' || f.status === 'PARTIAL')
      .reduce((sum, f) => sum + (f.amount - f.amount_paid), 0);
  }, [fines]);

  const outstandingFinesCount = useMemo(() => {
    return fines.filter(f => f.status === 'UNPAID' || f.status === 'PARTIAL').length;
  }, [fines]);

  const filteredFines = useMemo(() => {
    if (!statusFilter) return fines;
    return fines.filter(f => f.status === statusFilter);
  }, [fines, statusFilter]);

  const selectedFine = useMemo(() => {
    return fines.find(f => f.id === selectedFineId);
  }, [fines, selectedFineId]);

  const fetchMemberFines = useCallback(async () => {
    if (!currentUser?.memberId) {
      messageApi.error('Member ID not found');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      const result = await request<FineResponse[]>({
        method: 'GET',
        path: '/fines/',
        query: {
          member_id: currentUser.memberId,
          limit: 100
        }
      });
      setFines(result.data);
    } catch (error) {
      messageApi.error('Failed to load fines');
    } finally {
      setLoading(false);
    }
  }, [currentUser, messageApi]);

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

  const handleOpenPaymentModal = useCallback((fineId: string) => {
    setSelectedFineId(fineId);
    setPaymentModalVisible(true);
  }, []);

  const handleClosePaymentModal = useCallback(() => {
    setPaymentModalVisible(false);
    setSelectedFineId(null);
    form.resetFields();
  }, [form]);

  const handlePaymentSubmit = useCallback(async () => {
    if (!selectedFineId || !selectedFine) {
      messageApi.error('No fine selected');
      return;
    }

    try {
      const values = await form.validateFields();
      
      if (!values.amount || values.amount <= 0) {
        messageApi.error('Amount must be greater than 0');
        return;
      }

      Modal.confirm({
        title: 'Confirm Payment',
        content: `Are you sure you want to submit a payment of $${values.amount.toFixed(2)}?`,
        onOk: async () => {
          try {
            const remainingBalance = selectedFine.amount - selectedFine.amount_paid;
            const newAmountPaid = selectedFine.amount_paid + values.amount;
            const newStatus: FineStatus = newAmountPaid >= selectedFine.amount ? 'PAID' : 'PARTIAL';

            await request<FineResponse>({
              method: 'PUT',
              path: '/fines/{fine_id}',
              pathParams: { fine_id: selectedFineId },
              body: {
                amount_paid: newAmountPaid,
                status: newStatus
              }
            });

            messageApi.success('Payment submitted successfully!');
            handleClosePaymentModal();
            await fetchMemberFines();
          } catch (error) {
            messageApi.error('Payment failed. Please try again.');
          }
        }
      });
    } catch (error) {
      messageApi.error('Please fill in all required fields');
    }
  }, [selectedFineId, selectedFine, form, messageApi, handleClosePaymentModal, fetchMemberFines]);

  const navigateToDashboard = useCallback(() => {
    navigate(ROUTES.MEMBER_DASHBOARD || '/member/dashboard');
  }, [navigate]);

  const finesColumns = useMemo(() => [
    {
      title: 'Type',
      dataIndex: 'reason',
      key: 'reason',
      render: (reason: FineReason) => reason
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
      render: (description: string | null) => description || '-'
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `$${amount.toFixed(2)}`
    },
    {
      title: 'Paid',
      dataIndex: 'amount_paid',
      key: 'amount_paid',
      render: (amount_paid: number) => `$${amount_paid.toFixed(2)}`
    },
    {
      title: 'Date Assessed',
      dataIndex: 'assessed_date',
      key: 'assessed_date',
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: FineStatus) => {
        const colorMap: Record<FineStatus, string> = {
          UNPAID: 'red',
          PARTIAL: 'orange',
          PAID: 'green',
          WAIVED: 'blue'
        };
        return <span style={{ color: colorMap[status] }}>{status}</span>;
      }
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, record: FineResponse) => {
        if (record.status === 'UNPAID' || record.status === 'PARTIAL') {
          return (
            <Button
              type="primary"
              size="small"
              onClick={() => handleOpenPaymentModal(record.id)}
            >
              Pay Now
            </Button>
          );
        }
        return null;
      }
    }
  ], [handleOpenPaymentModal]);

  const paymentHistoryColumns = useMemo(() => [
    {
      title: 'Payment Date',
      dataIndex: 'payment_date',
      key: 'payment_date',
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `$${amount.toFixed(2)}`
    },
    {
      title: 'Method',
      dataIndex: 'payment_method',
      key: 'payment_method'
    },
    {
      title: 'Fine Applied To',
      dataIndex: 'fine_id',
      key: 'fine_id'
    },
    {
      title: 'Receipt #',
      dataIndex: 'receipt_number',
      key: 'receipt_number',
      render: (receipt: string | null) => receipt || '-'
    }
  ], []);

  return (
    <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column', padding: '24px', background: '#f5f5f5' }}>
      {contextHolder}
      
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <Typography.Title level={2} style={{ margin: 0 }}>
          My Fines
        </Typography.Title>
        <Button type="default" icon={<ArrowLeftOutlined />} onClick={navigateToDashboard}>
          Back to Dashboard
        </Button>
      </div>

      <Card bordered style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '48px' }}>
          <Statistic
            title="Total Outstanding Balance"
            value={totalOutstandingBalance}
            prefix="$"
            precision={2}
            valueStyle={{ color: '#cf1322' }}
          />
          <Statistic
            title="Outstanding Fines"
            value={outstandingFinesCount}
            valueStyle={{ color: '#faad14' }}
          />
        </div>
      </Card>

      <Card title="Outstanding Fines" bordered style={{ marginBottom: '24px' }}>
        <Select
          placeholder="All Statuses"
          allowClear
          value={statusFilter}
          onChange={(value) => setStatusFilter(value)}
          style={{ width: 200, marginBottom: '16px' }}
          options={[
            { label: 'Unpaid', value: 'UNPAID' },
            { label: 'Partial', value: 'PARTIAL' },
            { label: 'Paid', value: 'PAID' },
            { label: 'Waived', value: 'WAIVED' }
          ]}
        />
        <Table
          columns={finesColumns}
          dataSource={filteredFines}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 800 }}
        />
      </Card>

      <Card title="Payment History" bordered style={{ marginBottom: '24px' }}>
        <Table
          columns={paymentHistoryColumns}
          dataSource={payments}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 700 }}
        />
      </Card>

      <Card title="Fine Policies" bordered style={{ marginBottom: '24px' }}>
        <Alert
          type="info"
          showIcon
          message="Fine Policy Information"
          description="Daily fine rate: $0.50 per day per overdue book. Maximum fine cap: $25.00 per book. Account suspension threshold: $50.00 in outstanding fines. Fines begin accruing the day after the due date. Returning a book does not waive accrued overdue fines."
        />
      </Card>

      <Modal
        title="Pay Fine"
        open={paymentModalVisible}
        onOk={handlePaymentSubmit}
        onCancel={handleClosePaymentModal}
        okText="Submit Payment"
        cancelText="Cancel"
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="Payment Amount ($)"
            name="amount"
            rules={[{ required: true, message: 'Please enter payment amount' }]}
          >
            <InputNumber
              min={0.01}
              step={0.01}
              precision={2}
              placeholder="Enter amount"
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item
            label="Payment Method"
            name="payment_method"
            rules={[{ required: true, message: 'Please select a payment method' }]}
          >
            <Select
              placeholder="Select payment method"
              options={[
                { label: 'Credit Card', value: 'CREDIT_CARD' },
                { label: 'Debit Card', value: 'DEBIT_CARD' },
                { label: 'Online', value: 'ONLINE' }
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}