import { useState, useMemo, useEffect, useCallback } from 'react';
import { Card, Form, Input, Button, Avatar, Upload, Row, Col, Descriptions, Switch, Typography, message, Alert, Progress } from 'antd';
import { UserOutlined, ArrowLeftOutlined, EditOutlined } 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;
  phone: string | null;
  address: string | null;
  role: string;
  status: string;
  created_at: string;
  updated_at: string;
}

interface MemberResponse {
  id: string;
  user_id: string;
  membership_number: string;
  membership_date: string;
  membership_expiry: string | null;
  borrowing_limit: number;
  account_standing: string;
  created_at: string;
  updated_at: string;
}

interface NotificationPreferences {
  dueDateReminders: boolean;
  overdueNotifications: boolean;
  reservationNotifications: boolean;
  fineNotifications: boolean;
}

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

  const [userProfile, setUserProfile] = useState<UserResponse | null>(null);
  const [memberDetails, setMemberDetails] = useState<MemberResponse | null>(null);
  const [isEditingProfile, setIsEditingProfile] = useState<boolean>(false);
  const [isLoadingProfile, setIsLoadingProfile] = useState<boolean>(true);
  const [isSavingProfile, setIsSavingProfile] = useState<boolean>(false);
  const [isSavingPassword, setIsSavingPassword] = useState<boolean>(false);
  const [notificationPreferences, setNotificationPreferences] = useState<NotificationPreferences>({
    dueDateReminders: true,
    overdueNotifications: true,
    reservationNotifications: true,
    fineNotifications: true,
  });
  const [isSavingPreferences, setIsSavingPreferences] = useState<boolean>(false);
  const [profileError, setProfileError] = useState<string | null>(null);
  const [memberError, setMemberError] = useState<string | null>(null);

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

  const fullName = useMemo(() => {
    return (userProfile?.first_name || '') + ' ' + (userProfile?.last_name || '');
  }, [userProfile]);

  const membershipActive = useMemo(() => {
    return memberDetails?.account_standing === 'GOOD';
  }, [memberDetails]);

  useEffect(() => {
    const fetchUserProfile = async () => {
      if (!currentUser?.id) {
        setProfileError('User ID not found');
        setIsLoadingProfile(false);
        return;
      }

      try {
        const result = await request<UserResponse>({
          method: 'GET',
          path: '/users/{user_id}',
          pathParams: { user_id: currentUser.id },
        });
        setUserProfile(result.data);
        profileForm.setFieldsValue(result.data);
        setProfileError(null);
      } catch (error) {
        const errorMsg = 'Failed to load user profile';
        setProfileError(errorMsg);
        messageApi.error(errorMsg);
      } finally {
        setIsLoadingProfile(false);
      }
    };

    const fetchMemberDetails = async () => {
      if (!currentUser?.memberId) {
        setMemberError('Member ID not found');
        return;
      }

      try {
        const result = await request<MemberResponse>({
          method: 'GET',
          path: '/users/members/{member_id}',
          pathParams: { member_id: currentUser.memberId },
        });
        setMemberDetails(result.data);
        setMemberError(null);
      } catch (error) {
        const errorMsg = 'Failed to load member details';
        setMemberError(errorMsg);
        messageApi.error(errorMsg);
      }
    };

    fetchUserProfile();
    fetchMemberDetails();
  }, [currentUser, profileForm, messageApi]);

  const toggleEditMode = useCallback(() => {
    setIsEditingProfile(!isEditingProfile);
  }, [isEditingProfile]);

  const handleSaveProfile = useCallback(async () => {
    if (!currentUser?.id) {
      messageApi.error('User ID not found');
      return;
    }

    try {
      const formValues = await profileForm.validateFields();
      setIsSavingProfile(true);

      const result = await request<UserResponse>({
        method: 'PUT',
        path: '/users/{user_id}',
        pathParams: { user_id: currentUser.id },
        body: { phone: formValues.phone, address: formValues.address },
      });

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

  const handleSavePassword = useCallback(async () => {
    if (!currentUser?.id) {
      messageApi.error('User ID not found');
      return;
    }

    try {
      const formValues = await passwordForm.validateFields();

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

      setIsSavingPassword(true);

      await request<UserResponse>({
        method: 'PUT',
        path: '/users/{user_id}',
        pathParams: { user_id: currentUser.id },
        body: { password: formValues.new_password },
      });

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

  const handleSavePreferences = useCallback(async () => {
    setIsSavingPreferences(true);
    setTimeout(() => {
      setIsSavingPreferences(false);
      messageApi.success('Notification preferences saved!');
    }, 500);
  }, [messageApi]);

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

  const handleNotificationPrefChange = useCallback((key: keyof NotificationPreferences, value: boolean) => {
    setNotificationPreferences((prev) => ({ ...prev, [key]: value }));
  }, []);

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

      <div style={{ maxWidth: '900px', margin: '0 auto', width: '100%' }}>
        {profileError && (
          <Alert message="Error" description={profileError} type="error" showIcon style={{ marginBottom: '24px' }} />
        )}
        {memberError && (
          <Alert message="Error" description={memberError} type="error" showIcon style={{ marginBottom: '24px' }} />
        )}

        <Card title="Profile Photo" style={{ marginBottom: '24px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '24px' }}>
            <Avatar size={96} icon={<UserOutlined />} />
            <Upload accept="image/*" maxCount={1} listType="picture">
              <Button>Upload Photo</Button>
            </Upload>
          </div>
        </Card>

        <Card
          title="Personal Information"
          extra={
            <Button type="primary" icon={<EditOutlined />} onClick={toggleEditMode}>
              {isEditingProfile ? 'Cancel' : 'Edit Profile'}
            </Button>
          }
          style={{ marginBottom: '24px' }}
        >
          <Form form={profileForm} layout="vertical" disabled={!isEditingProfile} onFinish={handleSaveProfile}>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="First Name" name="first_name">
                  <Input disabled placeholder="First Name" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="Last Name" name="last_name">
                  <Input disabled placeholder="Last Name" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="Email" name="email">
                  <Input disabled placeholder="Email" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="Phone" name="phone">
                  <Input placeholder="Phone number" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={24}>
                <Form.Item label="Address" name="address">
                  <Input.TextArea rows={3} placeholder="Your address" />
                </Form.Item>
              </Col>
            </Row>

            <div style={{ marginTop: '16px', paddingTop: '16px', borderTop: '1px solid #f0f0f0' }}>
              <Typography.Title level={5} style={{ marginBottom: '12px' }}>
                Membership Details
              </Typography.Title>
              <Descriptions column={2} size="small" bordered>
                <Descriptions.Item label="Member ID">{memberDetails?.membership_number}</Descriptions.Item>
                <Descriptions.Item label="Membership Date">{memberDetails?.membership_date}</Descriptions.Item>
                <Descriptions.Item label="Expiry Date">{memberDetails?.membership_expiry || 'N/A'}</Descriptions.Item>
                <Descriptions.Item label="Account Standing">{memberDetails?.account_standing}</Descriptions.Item>
                <Descriptions.Item label="Borrowing Limit">{memberDetails?.borrowing_limit}</Descriptions.Item>
              </Descriptions>
            </div>

            {isEditingProfile && (
              <Button type="primary" htmlType="submit" loading={isSavingProfile} style={{ marginTop: '16px' }}>
                Save Profile
              </Button>
            )}
          </Form>
        </Card>

        <Card title="Change Password" style={{ marginBottom: '24px' }}>
          <Form form={passwordForm} layout="vertical" onFinish={handleSavePassword}>
            <Form.Item
              label="Current Password"
              name="current_password"
              rules={[{ required: true, message: 'Please enter your current password' }]}
            >
              <Input.Password placeholder="Enter current password" />
            </Form.Item>

            <Form.Item
              label="New Password"
              name="new_password"
              rules={[
                { required: true, message: 'Please enter a new password' },
                { min: 8, message: 'Password must be at least 8 characters' },
              ]}
            >
              <Input.Password placeholder="Enter new password" />
            </Form.Item>

            <Progress percent={0} size="small" showInfo style={{ marginBottom: '16px' }} />

            <Form.Item
              label="Confirm New Password"
              name="confirm_password"
              rules={[{ required: true, message: 'Please confirm your new password' }]}
            >
              <Input.Password placeholder="Confirm new password" />
            </Form.Item>

            <Button type="primary" htmlType="submit" loading={isSavingPassword}>
              Change Password
            </Button>
          </Form>
        </Card>

        <Card title="Notification Preferences" style={{ marginBottom: '24px' }}>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}>
              <Typography.Text>Email Due Date Reminders</Typography.Text>
              <Switch
                checked={notificationPreferences.dueDateReminders}
                onChange={(checked) => handleNotificationPrefChange('dueDateReminders', checked)}
              />
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}>
              <Typography.Text>Overdue Notifications</Typography.Text>
              <Switch
                checked={notificationPreferences.overdueNotifications}
                onChange={(checked) => handleNotificationPrefChange('overdueNotifications', checked)}
              />
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}>
              <Typography.Text>Reservation Notifications</Typography.Text>
              <Switch
                checked={notificationPreferences.reservationNotifications}
                onChange={(checked) => handleNotificationPrefChange('reservationNotifications', checked)}
              />
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
              <Typography.Text>Fine Notifications</Typography.Text>
              <Switch
                checked={notificationPreferences.fineNotifications}
                onChange={(checked) => handleNotificationPrefChange('fineNotifications', checked)}
              />
            </div>

            <Button type="primary" loading={isSavingPreferences} onClick={handleSavePreferences} style={{ marginTop: '16px' }}>
              Save Preferences
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
}