import { useState, useMemo, useEffect, useCallback } from 'react';
import { Layout, Card, Form, Input, Button, Row, Col, Space, Select, InputNumber, DatePicker, Radio, Statistic, Typography, Modal, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { UserService } from '@/services/user';
import { BmiService } from '@/services/bmi';
import { GoalService } from '@/services/goal';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';
import { useAppContext } from '@/store/AppStore';
import dayjs from 'dayjs';

type Gender = 'MALE' | 'FEMALE' | 'OTHER' | 'PREFER_NOT_TO_SAY';
type UnitSystem = 'METRIC' | 'IMPERIAL';
type GoalStatus = 'ACTIVE' | 'ACHIEVED' | 'ABANDONED';

interface UserDetailsResponse {
  id: string;
  user_id: string;
  email: string;
  first_name: string;
  last_name: string;
  date_of_birth: string | null;
  gender: Gender | null;
  is_active: boolean;
  role: string;
  last_login_at: string | null;
  created_at: string;
  updated_at: string;
  profile?: {
    preferred_unit?: UnitSystem;
    height_cm?: number;
    target_bmi?: number;
    target_weight?: number;
  } | null;
}

interface BmiCalculationResponse {
  id: string;
  calculation_id: string;
  user_id: string | null;
  height_cm: number;
  weight_kg: number;
  bmi_value: number;
  bmi_category: string;
  category_id: string | null;
  unit: string;
  calculated_at: string;
  notes: string | null;
  is_deleted: boolean;
  created_at: string;
  updated_at: string;
}

interface GoalResponse {
  id: string;
  goal_id: string;
  user_id: string;
  goal_type: string;
  target_value: number;
  current_value: number | null;
  start_date: string;
  target_date: string;
  status: string;
  created_at: string;
  updated_at: string;
}

const ProfilePage = () => {
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const { currentUser } = useAppContext();
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();

  const [userDetails, setUserDetails] = useState<UserDetailsResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [saving, setSaving] = useState<boolean>(false);
  const [changePasswordModalVisible, setChangePasswordModalVisible] = useState<boolean>(false);
  const [deleteConfirmModalVisible, setDeleteConfirmModalVisible] = useState<boolean>(false);
  const [calculationCount, setCalculationCount] = useState<number>(0);
  const [lastCalculation, setLastCalculation] = useState<BmiCalculationResponse | null>(null);
  const [activeGoals, setActiveGoals] = useState<GoalResponse[]>([]);

  const { data: userDetailsData, loading: userDetailsLoading, error: userDetailsError, execute: fetchUserDetails } = useApi(
    (userId: string) => UserService.getDetails(userId)
  );

  const { data: lastCalcData, execute: fetchLastCalculation } = useApi(
    (userId: string) => BmiService.listCalculations({ user_id: userId, limit: 1, is_deleted: false })
  );

  const { data: allCalcsData, execute: fetchAllCalculations } = useApi(
    (userId: string) => BmiService.listCalculations({ user_id: userId, is_deleted: false, limit: 1000 })
  );

  const { data: goalsData, execute: fetchGoals } = useApi(
    (userId: string) => GoalService.getUserGoals(userId, { status: 'ACTIVE' as GoalStatus, limit: 5 })
  );

  useEffect(() => {
    const loadData = async () => {
      if (!currentUser?.userId) {
        navigate(ROUTES.LOGIN);
        return;
      }

      try {
        setLoading(true);
        await Promise.all([
          fetchUserDetails(currentUser.userId),
          fetchLastCalculation(currentUser.userId),
          fetchAllCalculations(currentUser.userId),
          fetchGoals(currentUser.userId)
        ]);
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      } finally {
        setLoading(false);
      }
    };

    void loadData();
  }, [currentUser, fetchUserDetails, fetchLastCalculation, fetchAllCalculations, fetchGoals, messageApi, navigate]);

  useEffect(() => {
    if (userDetailsData) {
      setUserDetails(userDetailsData);
      form.setFieldsValue({
        first_name: userDetailsData.first_name,
        last_name: userDetailsData.last_name,
        date_of_birth: userDetailsData.date_of_birth ? dayjs(userDetailsData.date_of_birth) : null,
        gender: userDetailsData.gender,
        preferred_unit: userDetailsData.profile?.preferred_unit || 'METRIC',
        height_cm: userDetailsData.profile?.height_cm,
        target_bmi: userDetailsData.profile?.target_bmi,
        target_weight: userDetailsData.profile?.target_weight
      });
    }
  }, [userDetailsData, form]);

  useEffect(() => {
    if (lastCalcData && Array.isArray(lastCalcData) && lastCalcData.length > 0) {
      setLastCalculation(lastCalcData[0]);
    }
  }, [lastCalcData]);

  useEffect(() => {
    if (allCalcsData && Array.isArray(allCalcsData)) {
      setCalculationCount(allCalcsData.length);
    }
  }, [allCalcsData]);

  useEffect(() => {
    if (goalsData && Array.isArray(goalsData)) {
      setActiveGoals(goalsData);
    }
  }, [goalsData]);

  const computedAge = useMemo(() => {
    if (!userDetails?.date_of_birth) return null;
    return Math.floor((Date.now() - new Date(userDetails.date_of_birth).getTime()) / (365.25 * 24 * 60 * 60 * 1000));
  }, [userDetails]);

  const currentBMI = useMemo(() => {
    return lastCalculation?.bmi_value ?? null;
  }, [lastCalculation]);

  const lastCalculationDate = useMemo(() => {
    return lastCalculation?.calculated_at ?? null;
  }, [lastCalculation]);

  const currentGoalStatus = useMemo(() => {
    return activeGoals.length > 0 ? activeGoals[0].status : 'No active goals';
  }, [activeGoals]);

  const handleSaveProfile = async () => {
    if (!currentUser?.userId) return;

    try {
      setSaving(true);
      const values = await form.validateFields();

      const updatePayload = {
        first_name: values.first_name,
        last_name: values.last_name,
        date_of_birth: values.date_of_birth ? dayjs(values.date_of_birth).format('YYYY-MM-DD') : null,
        gender: values.gender
      };

      const response = await UserService.update(currentUser.userId, updatePayload);
      setUserDetails(response.data);
      messageApi.success('Profile updated successfully!');
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Failed to update profile. Please try again.');
    } finally {
      setSaving(false);
    }
  };

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

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

      messageApi.success('Password changed successfully!');
      setChangePasswordModalVisible(false);
      passwordForm.resetFields();
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Failed to change password. Please check your current password.');
    }
  };

  const handleDeleteAccount = async () => {
    if (!currentUser?.userId) return;

    try {
      await UserService.delete(currentUser.userId);
      messageApi.info('Account deletion requested. You will be logged out.');
      setDeleteConfirmModalVisible(false);
      setTimeout(() => {
        navigate(ROUTES.LOGIN);
      }, 1500);
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Failed to process account deletion request.');
    }
  };

  const openChangePasswordModal = useCallback(() => {
    setChangePasswordModalVisible(true);
  }, []);

  const closeChangePasswordModal = useCallback(() => {
    setChangePasswordModalVisible(false);
    passwordForm.resetFields();
  }, [passwordForm]);

  const openDeleteConfirmModal = useCallback(() => {
    setDeleteConfirmModalVisible(true);
  }, []);

  const closeDeleteConfirmModal = useCallback(() => {
    setDeleteConfirmModalVisible(false);
  }, []);

  const navigateToCalculator = useCallback(() => {
    navigate(ROUTES.HOME);
  }, [navigate]);

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

  const navigateToHistory = useCallback(() => {
    navigate(ROUTES.HISTORY);
  }, [navigate]);

  const navigateToGoals = useCallback(() => {
    navigate(ROUTES.GOALS);
  }, [navigate]);

  return (
    <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column' }}>
      {contextHolder}
      <Layout style={{ minHeight: '100vh', width: '100%', background: '#f5f5f5' }}>
        <div style={{ padding: '24px', background: '#fff', marginBottom: '24px' }}>
          <Typography.Title level={3} style={{ margin: 0 }}>My Profile</Typography.Title>
          <Typography.Text type="secondary">Manage your personal information and account settings</Typography.Text>
        </div>

        <Space size="middle" style={{ padding: '0 24px', marginBottom: '24px' }}>
          <Button type="link" onClick={navigateToCalculator}>Calculator</Button>
          <Button type="link" onClick={navigateToDashboard}>Dashboard</Button>
          <Button type="link" onClick={navigateToHistory}>History</Button>
          <Button type="link" onClick={navigateToGoals}>Goals</Button>
        </Space>

        <Row gutter={[24, 24]} style={{ padding: '0 24px' }}>
          <Col xs={24} lg={16}>
            <Card title="Personal Information" style={{ marginBottom: '24px' }}>
              <Form
                form={form}
                layout="vertical"
                name="profile_form"
                onFinish={handleSaveProfile}
              >
                <Row gutter={16}>
                  <Col xs={24} sm={12}>
                    <Form.Item
                      name="first_name"
                      label="First Name"
                      rules={[{ required: true, message: 'First name is required' }]}
                    >
                      <Input placeholder="Enter your first name" />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={12}>
                    <Form.Item
                      name="last_name"
                      label="Last Name"
                      rules={[{ required: true, message: 'Last name is required' }]}
                    >
                      <Input placeholder="Enter your last name" />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col xs={24} sm={12}>
                    <Form.Item name="date_of_birth" label="Date of Birth">
                      <DatePicker style={{ width: '100%' }} placeholder="Select date of birth" />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={12}>
                    <Form.Item name="gender" label="Gender">
                      <Select
                        placeholder="Select gender"
                        allowClear
                        options={[
                          { label: 'Male', value: 'MALE' },
                          { label: 'Female', value: 'FEMALE' },
                          { label: 'Other', value: 'OTHER' },
                          { label: 'Prefer not to say', value: 'PREFER_NOT_TO_SAY' }
                        ]}
                      />
                    </Form.Item>
                  </Col>
                </Row>

                {computedAge !== null && (
                  <Typography.Text type="secondary" style={{ marginBottom: '16px', display: 'block' }}>
                    Age: {computedAge} years
                  </Typography.Text>
                )}

                <Row gutter={16}>
                  <Col xs={24} sm={12}>
                    <Form.Item name="preferred_unit" label="Preferred Unit System">
                      <Radio.Group
                        optionType="button"
                        buttonStyle="solid"
                        options={[
                          { label: 'Metric', value: 'METRIC' },
                          { label: 'Imperial', value: 'IMPERIAL' }
                        ]}
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={12}>
                    <Form.Item name="height_cm" label="Default Height (cm)">
                      <InputNumber
                        min={50}
                        max={300}
                        placeholder="Height in cm"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col xs={24} sm={12}>
                    <Form.Item name="target_bmi" label="Target BMI">
                      <InputNumber
                        min={15}
                        max={40}
                        step={0.1}
                        placeholder="e.g. 22.0"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={12}>
                    <Form.Item name="target_weight" label="Target Weight (kg)">
                      <InputNumber
                        min={30}
                        max={300}
                        step={0.5}
                        placeholder="e.g. 70.0"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Button
                  type="primary"
                  htmlType="submit"
                  loading={saving}
                  size="large"
                  style={{ marginTop: '16px' }}
                >
                  Save Profile
                </Button>
              </Form>
            </Card>
          </Col>

          <Col xs={24} lg={8}>
            <Card title="Profile Summary" style={{ marginBottom: '24px' }}>
              <Space direction="vertical" size="large" style={{ width: '100%' }}>
                <Statistic
                  title="Current BMI"
                  value={currentBMI ?? 0}
                  precision={1}
                  suffix="kg/m²"
                />
                <Statistic
                  title="Last Calculation"
                  value={lastCalculationDate ? dayjs(lastCalculationDate).format('MMM DD, YYYY') : 'N/A'}
                />
                <Statistic
                  title="Total Calculations"
                  value={calculationCount}
                />
                <Statistic
                  title="Current Goal Status"
                  value={currentGoalStatus}
                />
              </Space>
            </Card>

            <Card title="Account Actions">
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <Button type="default" block onClick={openChangePasswordModal}>
                  Change Password
                </Button>
                <Button type="default" danger block onClick={openDeleteConfirmModal}>
                  Request Account Deletion
                </Button>
              </Space>
            </Card>
          </Col>
        </Row>
      </Layout>

      <Modal
        title="Change Password"
        open={changePasswordModalVisible}
        onOk={handleChangePassword}
        onCancel={closeChangePasswordModal}
        okText="Change Password"
        cancelText="Cancel"
      >
        <Form form={passwordForm} layout="vertical" name="change_password_form">
          <Form.Item
            name="current_password"
            label="Current Password"
            rules={[{ required: true, message: 'Current password is required' }]}
          >
            <Input.Password placeholder="Enter current password" />
          </Form.Item>
          <Form.Item
            name="new_password"
            label="New Password"
            rules={[
              { required: true, message: 'New password is required' },
              { min: 8, message: 'Password must be at least 8 characters' }
            ]}
          >
            <Input.Password placeholder="Enter new password" />
          </Form.Item>
          <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>
        </Form>
      </Modal>

      <Modal
        title="Confirm Account Deletion"
        open={deleteConfirmModalVisible}
        onOk={handleDeleteAccount}
        onCancel={closeDeleteConfirmModal}
        okText="Delete My Account"
        okButtonProps={{ danger: true }}
        cancelText="Cancel"
      >
        <Typography.Paragraph type="danger">
          Are you sure you want to delete your account? This action cannot be undone. All your data, including BMI calculations and goals, will be permanently removed.
        </Typography.Paragraph>
      </Modal>
    </div>
  );
};

export default ProfilePage;