import { useState, useMemo, useEffect, useCallback, CSSProperties } from 'react';
import { Card, Row, Col, Statistic, Tag, Typography, Form, Input, Button, message, Alert, Spin } from 'antd';
import { ArrowLeftOutlined, BookOutlined } 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';

interface UserResponse {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
}

interface MemberDetailResponse {
  id: string;
  membership_number: string;
  user: UserResponse;
  library_branch: Record<string, unknown> | null;
  membership_status?: 'ACTIVE' | 'SUSPENDED' | 'EXPIRED' | 'CANCELLED';
  join_date?: string;
  date_of_birth?: string | null;
  address?: string | null;
}

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: 'ACTIVE' | 'RETURNED' | 'OVERDUE' | 'LOST';
  checked_out_by_librarian_id: string | null;
  checked_in_by_librarian_id: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface FineResponse {
  id: string;
  member_id: string;
  loan_id: string | null;
  amount: string;
  reason: string;
  issue_date: string;
  payment_status: 'UNPAID' | 'PARTIALLY_PAID' | 'PAID' | 'WAIVED';
  payment_date: string | null;
  amount_paid: string;
  waived_by_librarian_id: string | null;
  waived_reason: string | null;
  created_at: string;
  updated_at: string;
}

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

  const [memberDetails, setMemberDetails] = useState<MemberDetailResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [savingProfile, setSavingProfile] = useState<boolean>(false);
  const [savingPassword, setSavingPassword] = useState<boolean>(false);
  const [loans, setLoans] = useState<LoanResponse[]>([]);
  const [fines, setFines] = useState<FineResponse[]>([]);
  const [fetchError, setFetchError] = useState<string | null>(null);

  const [profileForm] = Form.useForm();
  const [passwordForm] = Form.useForm();

  const membershipStatusColor = useMemo(() => {
    if (!memberDetails) return 'default';
    switch (memberDetails.membership_status) {
      case 'ACTIVE':
        return 'green';
      case 'SUSPENDED':
        return 'red';
      case 'EXPIRED':
        return 'orange';
      default:
        return 'default';
    }
  }, [memberDetails]);

  const totalBorrowed = useMemo(() => loans.length, [loans]);

  const activeLoansCount = useMemo(
    () => loans.filter((l) => l.status === 'ACTIVE').length,
    [loans]
  );

  const totalFinesPaid = useMemo(
    () =>
      fines
        .filter((f) => f.payment_status === 'PAID')
        .reduce((sum, f) => sum + Number(f.amount_paid || 0), 0),
    [fines]
  );

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setFetchError(null);
      try {
        const memberId = (currentUser as { memberId?: string })?.memberId;
        if (!memberId) {
          throw new Error('Member ID not found in current user context');
        }

        const [memberRes, loansRes, finesRes] = await Promise.all([
          request<MemberDetailResponse>({
            method: 'GET',
            path: '/auth/members/{member_id}/details',
            pathParams: { member_id: memberId },
          }),
          request<LoanResponse[]>({
            method: 'GET',
            path: '/loans/',
            query: { member_id: memberId, limit: 100 },
          }),
          request<FineResponse[]>({
            method: 'GET',
            path: '/fines/',
            query: { member_id: memberId, limit: 100 },
          }),
        ]);

        setMemberDetails(memberRes.data);
        setLoans(loansRes.data);
        setFines(finesRes.data);

        profileForm.setFieldsValue({
          full_name: `${memberRes.data.user.first_name} ${memberRes.data.user.last_name}`,
          email: memberRes.data.user.email,
          phone: (memberRes.data.user as { phone?: string }).phone || '',
          address: memberRes.data.address || '',
        });
      } catch (error) {
        const errorMsg = 'Failed to load profile data';
        setFetchError(errorMsg);
        messageApi.error(errorMsg);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [currentUser, messageApi, profileForm]);

  const handleSaveProfile = useCallback(async () => {
    try {
      const values = await profileForm.validateFields();
      setSavingProfile(true);

      const userId = currentUser?.id;
      const memberId = (currentUser as { memberId?: string })?.memberId;

      if (!userId || !memberId) {
        throw new Error('User or Member ID not found');
      }

      const nameParts = (memberDetails?.user.first_name + ' ' + memberDetails?.user.last_name).split(' ');
      const firstName = nameParts[0] || '';
      const lastName = nameParts.slice(1).join(' ') || '';

      await request({
        method: 'PUT',
        path: '/auth/users/{user_id}',
        pathParams: { user_id: userId },
        body: {
          email: values.email,
          phone: values.phone,
          first_name: firstName,
          last_name: lastName,
        },
      });

      await request({
        method: 'PUT',
        path: '/auth/members/{member_id}',
        pathParams: { member_id: memberId },
        body: {
          address: values.address,
        },
      });

      messageApi.success('Profile updated successfully!');
    } catch (error) {
      messageApi.error('Failed to update profile. Please try again.');
    } finally {
      setSavingProfile(false);
    }
  }, [profileForm, currentUser, memberDetails, messageApi]);

  const handleChangePassword = useCallback(async () => {
    try {
      const values = await passwordForm.validateFields();

      if (values.new_password !== values.confirm_password) {
        messageApi.error('New password and confirmation do not match');
        return;
      }

      setSavingPassword(true);

      const userId = currentUser?.id;
      if (!userId) {
        throw new Error('User ID not found');
      }

      await request({
        method: 'PUT',
        path: '/auth/users/{user_id}',
        pathParams: { user_id: userId },
        body: {
          password: values.new_password,
        },
      });

      messageApi.success('Password changed successfully!');
      passwordForm.resetFields();
    } catch (error) {
      messageApi.error('Failed to change password. Please check your current password.');
    } finally {
      setSavingPassword(false);
    }
  }, [passwordForm, currentUser, messageApi]);

  const handleNavigateToDashboard = useCallback(() => {
    navigate(ROUTES.DASHBOARD || '/dashboard');
  }, [navigate]);

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

  const pageHeaderStyle: CSSProperties = {
    marginBottom: '24px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
  };

  if (loading) {
    return (
      <div style={rootStyle}>
        {contextHolder}
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }}>
          <Spin size="large" />
        </div>
      </div>
    );
  }

  return (
    <div style={rootStyle}>
      {contextHolder}

      {fetchError && (
        <Alert
          message="Error"
          description={fetchError}
          type="error"
          closable
          style={{ marginBottom: '24px' }}
        />
      )}

      <div style={pageHeaderStyle}>
        <Typography.Title level={2} style={{ margin: 0 }}>
          My Profile
        </Typography.Title>
        <Button type="default" icon={<ArrowLeftOutlined />} onClick={handleNavigateToDashboard}>
          Back to Dashboard
        </Button>
      </div>

      <Card title="Membership Information" style={{ marginBottom: '24px' }}>
        <Row gutter={[24, 16]}>
          <Col xs={24} sm={8}>
            <Statistic title="Membership Number" value={memberDetails?.membership_number || 'N/A'} />
          </Col>
          <Col xs={24} sm={8}>
            <Statistic title="Join Date" value={memberDetails?.join_date || 'N/A'} />
          </Col>
          <Col xs={24} sm={8}>
            <div>
              <Typography.Text type="secondary" style={{ display: 'block', marginBottom: '8px' }}>
                Membership Status
              </Typography.Text>
              <Tag color={membershipStatusColor} style={{ fontSize: '14px', padding: '4px 12px' }}>
                {memberDetails?.membership_status || 'UNKNOWN'}
              </Tag>
            </div>
          </Col>
        </Row>
      </Card>

      <Card title="Borrowing Statistics" style={{ marginBottom: '24px' }}>
        <Row gutter={[24, 16]}>
          <Col xs={24} sm={8}>
            <Statistic title="Total Books Borrowed" value={totalBorrowed} prefix={<BookOutlined />} />
          </Col>
          <Col xs={24} sm={8}>
            <Statistic
              title="Current Active Loans"
              value={activeLoansCount}
              valueStyle={{ color: '#1677ff' }}
            />
          </Col>
          <Col xs={24} sm={8}>
            <Statistic title="Total Fines Paid" value={totalFinesPaid} prefix="$" precision={2} />
          </Col>
        </Row>
      </Card>

      <Card title="Profile Information" style={{ marginBottom: '24px' }}>
        <Form form={profileForm} layout="vertical" name="profile_form" onFinish={handleSaveProfile}>
          <Row gutter={24}>
            <Col xs={24} sm={12}>
              <Form.Item name="full_name" label="Full Name">
                <Input disabled placeholder="Full Name" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name="email"
                label="Email"
                rules={[{ required: true, type: 'email', message: 'Please enter a valid email' }]}
              >
                <Input placeholder="Enter your email" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col xs={24} sm={12}>
              <Form.Item name="phone" label="Phone Number">
                <Input placeholder="Enter your phone number" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item name="address" label="Address">
                <Input.TextArea placeholder="Enter your address" rows={3} />
              </Form.Item>
            </Col>
          </Row>
          <Button type="primary" htmlType="submit" loading={savingProfile}>
            Save Changes
          </Button>
        </Form>
      </Card>

      <Card title="Change Password" style={{ marginBottom: '24px' }}>
        <Form form={passwordForm} layout="vertical" name="password_form" onFinish={handleChangePassword}>
          <Row gutter={24}>
            <Col xs={24} sm={8}>
              <Form.Item
                name="current_password"
                label="Current Password"
                rules={[{ required: true, message: 'Please enter your current password' }]}
              >
                <Input.Password placeholder="Current password" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={8}>
              <Form.Item
                name="new_password"
                label="New Password"
                rules={[
                  { required: true, min: 8, message: 'Password must be at least 8 characters' },
                ]}
              >
                <Input.Password placeholder="New password" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={8}>
              <Form.Item
                name="confirm_password"
                label="Confirm New Password"
                rules={[{ required: true, message: 'Please confirm your new password' }]}
              >
                <Input.Password placeholder="Confirm new password" />
              </Form.Item>
            </Col>
          </Row>
          <Button type="primary" htmlType="submit" loading={savingPassword}>
            Change Password
          </Button>
        </Form>
      </Card>
    </div>
  );
}