import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Divider, Select, Steps, Upload, Image, Typography } from 'antd';
import { UserOutlined, PhoneOutlined, MailOutlined, HomeOutlined, EnvironmentOutlined, UploadOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;
import { useNavigate } from 'react-router-dom';
import api from '../../utils/api';
import { colors, spacing, commonStyles } from '../../theme';

const { TextArea } = Input;

function New() {
  const navigate = useNavigate();
  const [wordCount, setWordCount] = useState(0);
  const [currentStep, setCurrentStep] = useState(0);
  const [accountNumber, setAccountNumber] = useState('');
  const [uploadedImages, setUploadedImages] = useState([]);
  const [form] = Form.useForm();

  const steps = [
    {
      title: 'Customer Information',
      content: 'Step 1',
    },
    {
      title: 'Account Setup',
      content: 'Step 2',
    },
    {
      title: 'Tank Inspection',
      content: 'Step 3',
    },
  ];

  const handleDescriptionChange = (e) => {
    const value = e.target.value;
    const words = value.trim() === '' ? 0 : value.trim().split(/\s+/).length;
    setWordCount(words);
  };

  const formatPhoneNumber = (value) => {
    // Remove all non-digit characters
    const phoneNumber = value.replace(/\D/g, '');

    // Limit to 10 digits
    const limitedPhoneNumber = phoneNumber.slice(0, 10);

    // Format as (XXX) XXX-XXXX
    if (limitedPhoneNumber.length >= 6) {
      return `(${limitedPhoneNumber.slice(0, 3)}) ${limitedPhoneNumber.slice(3, 6)}-${limitedPhoneNumber.slice(6)}`;
    } else if (limitedPhoneNumber.length >= 3) {
      return `(${limitedPhoneNumber.slice(0, 3)}) ${limitedPhoneNumber.slice(3)}`;
    } else if (limitedPhoneNumber.length > 0) {
      return `(${limitedPhoneNumber}`;
    }
    return limitedPhoneNumber;
  };

  const handlePhoneNumberChange = (e) => {
    const formattedValue = formatPhoneNumber(e.target.value);
    form.setFieldsValue({ customer_phone_number: formattedValue });
  };

  const handleNameChange = (fieldName) => (e) => {
    const value = e.target.value;
    // Capitalize first letter of each word (title case)
    const formattedValue = value.replace(/\b\w/g, (char) => char.toUpperCase());
    form.setFieldsValue({ [fieldName]: formattedValue });
  };

  const handleTownChange = (e) => {
    const value = e.target.value;
    // Capitalize first letter of each word for town names
    const formattedValue = value.replace(/\b\w/g, (char) => char.toUpperCase());
    form.setFieldsValue({ customer_town: formattedValue });
  };

  const next = async () => {
    try {
      if (currentStep === 0) {
        // Validate step 1 fields
        await form.validateFields([
          'customer_first_name', 'customer_last_name', 'customer_phone_number',
          'customer_address', 'customer_town', 'customer_zip', 'customer_home_type'
        ]);
        // Submit step 1 - get formatted phone number
        const rawData = form.getFieldsValue([
          'customer_first_name', 'customer_last_name', 'customer_phone_number',
          'customer_address', 'customer_apt', 'customer_town', 'customer_zip',
          'customer_home_type', 'house_description'
        ]);

        // Send formatted phone number to backend
        const step1Data = {
          ...rawData,
          customer_phone_number: rawData.customer_phone_number // Already formatted by handlePhoneNumberChange
        };
        const response = await api.post('/auth/step1', step1Data);
        setAccountNumber(response.data.account_number);
        setCurrentStep(currentStep + 1);
      } else if (currentStep === 1) {
        // Validate step 2 fields
        await form.validateFields(['password', 'confirm_password', 'customer_email']);
        // Submit step 2
        const step2Data = {
          account_number: accountNumber,
          password: form.getFieldValue('password'),
          confirm_password: form.getFieldValue('confirm_password'),
          customer_email: form.getFieldValue('customer_email')
        };
        await api.post('/auth/step2', step2Data);
        setCurrentStep(currentStep + 1);
      }
    } catch (error) {
      if (error.response) {
        message.error(`Step ${currentStep + 1} failed: ` + (error.response.data?.detail || 'Unknown error'));
      }
      // Validation errors are handled by form
    }
  };

  const prev = () => {
    setCurrentStep(currentStep - 1);
  };

  const onFinish = async (values, skipImages = false) => {
    if (currentStep === 2) {
      if (!skipImages && uploadedImages.length < 3) {
        message.error('Please upload all 3 tank images or skip for now');
        return;
      }

      try {
        if (!skipImages) {
          // Upload tank images
          const formData = new FormData();
          formData.append('account_number', accountNumber);

          // Get uploaded files from state
          uploadedImages.forEach((file, index) => {
            formData.append(`tank_image_${index + 1}`, file.originFileObj);
          });

          await api.post('/auth/step3', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          });
        }

        message.success('Customer registration completed successfully!');
        navigate('/login?registered=true');
      } catch (error) {
        if (error.response?.status === 400 && error.response.data?.detail) {
          message.error(error.response.data.detail);
        } else {
          message.error('Registration failed: ' + (error.response?.data?.detail || 'Unknown error'));
        }
      }
    }
  };

  const handleSkipImages = () => {
    onFinish(null, true);
  };

  return (
    <Card title="New Customer Registration" style={{ maxWidth: 600, margin: '0 auto', ...commonStyles.cardGray }}>
      <Steps current={currentStep} items={steps} style={{ marginBottom: 24 }} />
      <Form
        name="new-customer"
        form={form}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
        initialValues={{ customer_home_type: 0 }}
      >
        {currentStep === 0 && (
          <>
            <Divider>General Info</Divider>

        <Form.Item
          name="customer_first_name"
          label="First Name"
          hasFeedback
          rules={[
            { required: true, message: 'Please input your first name!' },
            { min: 2, message: 'First name must be at least 2 characters' },
            { max: 50, message: 'First name must be no more than 50 characters' }
          ]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="First Name"
            onChange={handleNameChange('customer_first_name')}
          />
        </Form.Item>

        <Form.Item
          name="customer_last_name"
          label="Last Name"
          hasFeedback
          rules={[
            { required: true, message: 'Please input your last name!' },
            { min: 2, message: 'Last name must be at least 2 characters' },
            { max: 50, message: 'Last name must be no more than 50 characters' }
          ]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="Last Name"
            onChange={handleNameChange('customer_last_name')}
          />
        </Form.Item>

        <Form.Item
          name="customer_phone_number"
          label="Phone Number"
          hasFeedback
          rules={[
            { required: true, message: 'Please input your phone number!' },
            {
              validator: (_, value) => {
                const digitsOnly = value ? value.replace(/\D/g, '') : '';
                if (digitsOnly.length !== 10) {
                  return Promise.reject('Phone number must be 10 digits');
                }
                return Promise.resolve();
              }
            }
          ]}
        >
          <Input
            prefix={<PhoneOutlined />}
            placeholder="Phone Number (10 digits)"
            onChange={handlePhoneNumberChange}
          />
        </Form.Item>

        <Form.Item
          name="customer_address"
          label="Street Address"
          hasFeedback
          rules={[
            { required: true, message: 'Please input your street address!' },
            { min: 3, message: 'Street address must be at least 3 characters' },
            { max: 100, message: 'Street address must be no more than 100 characters' }
          ]}
        >
          <Input prefix={<HomeOutlined />} placeholder="Street Address" />
        </Form.Item>

        <Form.Item
          name="customer_apt"
          label="Apt, suite, unit..."
        >
          <Input placeholder="Apt, suite, unit..." />
        </Form.Item>

        <Form.Item
          name="customer_town"
          label="Town"
          hasFeedback
          rules={[
            { required: true, message: 'Please input your town!' },
            { min: 3, message: 'Town must be at least 3 characters' },
            { max: 25, message: 'Town must be no more than 25 characters' }
          ]}
        >
          <Input
            prefix={<EnvironmentOutlined />}
            placeholder="Town"
            onChange={handleTownChange}
          />
        </Form.Item>

        <Form.Item label="State">
          <Input value="MA" disabled style={{ color: '#000', backgroundColor: '#f5f5f5' }} />
        </Form.Item>

        <Form.Item
          name="customer_zip"
          label="Zip Code"
          hasFeedback
          rules={[
            { required: true, message: 'Please input your zip code!' },
            { len: 5, message: 'Zip code must be exactly 5 characters' }
          ]}
        >
          <Input placeholder="Zip Code" />
        </Form.Item>

        <Form.Item
          name="customer_home_type"
          label="Home Type"
          hasFeedback
          rules={[{ required: true, message: 'Please select your home type!' }]}
        >
          <Select placeholder="Select home type">
            <Select.Option value={0}>Residential</Select.Option>
            <Select.Option value={1}>apartment</Select.Option>
            <Select.Option value={2}>condo</Select.Option>
            <Select.Option value={3}>commercial</Select.Option>
            <Select.Option value={4}>business</Select.Option>
            <Select.Option value={5}>construction</Select.Option>
            <Select.Option value={6}>container</Select.Option>
          </Select>
        </Form.Item>

        <Divider>Delivery Details</Divider>

        <Form.Item
          name="house_description"
          label="Customer House Description (20 words or less, optional)"
          hasFeedback
          validateStatus={wordCount > 20 ? 'error' : wordCount > 0 ? 'success' : ''}
          help={<span style={{ color: wordCount > 20 ? 'red' : 'green' }}>{wordCount}/20 words{wordCount > 20 ? ' (exceeded limit)' : ''}</span>}
          rules={[
            {
              validator: (_, value) => {
                if (value && value.split(' ').length > 20) {
                  return Promise.reject('Description must be 20 words or less');
                }
                return Promise.resolve();
              }
            }
          ]}
        >
          <TextArea placeholder="House Description" rows={4} onChange={handleDescriptionChange} />
        </Form.Item>
          </>
        )}

        {currentStep === 1 && (
          <>
            <div style={{ textAlign: 'center', marginBottom: 24, fontSize: 16, fontWeight: 'bold' }}>
              Your account number is: {accountNumber}
            </div>

            <Divider>Account Setup</Divider>

            <Form.Item
              name="password"
              label="Password"
              hasFeedback
              rules={[{ required: true, message: 'Please input your password!' }]}
            >
              <Input.Password placeholder="Password" />
            </Form.Item>

            <Form.Item
              name="confirm_password"
              label="Confirm Password"
              dependencies={['password']}
              hasFeedback
              rules={[
                { required: true, message: 'Please confirm your password!' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('The two passwords do not match!'));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="Confirm Password" />
            </Form.Item>

            <Form.Item
              name="customer_email"
              label="Email"
              hasFeedback
              rules={[
                { required: true, message: 'Please input your email!' },
                { type: 'email', message: 'Please enter a valid email!' }
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="Email" />
            </Form.Item>
          </>
        )}

        {currentStep === 2 && (
          <>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Title level={4}>Please take 3 images of your tank</Title>
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-around', marginBottom: 24 }}>
              <div style={{ textAlign: 'center' }}>
                <Image
                  width={150}
                  src="/src/assets/images/tank_example/tank_1.jpg"
                  alt="General picture of tank"
                  style={{ marginBottom: 8 }}
                />
                <p style={{ fontSize: 14 }}>General picture of your tank</p>
              </div>
              <div style={{ textAlign: 'center' }}>
                <Image
                  width={150}
                  src="/src/assets/images/tank_example/tank_2.jpg"
                  alt="Picture of legs of tank"
                  style={{ marginBottom: 8 }}
                />
                <p style={{ fontSize: 14 }}>Picture of legs of your tank</p>
              </div>
              <div style={{ textAlign: 'center' }}>
                <Image
                  width={150}
                  src="/src/assets/images/tank_example/tank_3.jpg"
                  alt="Picture of front of tank"
                  style={{ marginBottom: 8 }}
                />
                <p style={{ fontSize: 14 }}>Picture of front of your tank</p>
              </div>
            </div>

            <Divider>Tank Images</Divider>

            <Form.Item
              label="Upload Tank Images (3 required)"
              rules={[
                {
                  validator: () => {
                    if (uploadedImages.length === 3) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('Please upload all 3 tank images'));
                  }
                }
              ]}
            >
              <Upload
                listType="picture-card"
                fileList={uploadedImages}
                onChange={({ fileList }) => setUploadedImages(fileList)}
                beforeUpload={() => false} // Prevent auto upload
                multiple
                maxCount={3}
                accept="image/*"
              >
                {uploadedImages.length < 3 && (
                  <div>
                    <UploadOutlined />
                    <div style={{ marginTop: 8 }}>Upload</div>
                  </div>
                )}
              </Upload>
            </Form.Item>

            {uploadedImages.length === 3 && (
              <div style={{ marginTop: 16 }}>
                <Title level={5}>Uploaded Images Preview:</Title>
                <div style={{ display: 'flex', justifyContent: 'space-around', marginTop: 16 }}>
                  {uploadedImages.map((file, index) => (
                    <div key={index} style={{ textAlign: 'center' }}>
                      <Image
                        width={120}
                        src={URL.createObjectURL(file.originFileObj)}
                        alt={`Tank image ${index + 1}`}
                        style={{ marginBottom: 8 }}
                      />
                      <p style={{ fontSize: 12 }}>Image {index + 1}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}

        <Form.Item style={{ marginTop: 24 }}>
          {currentStep === 0 && (
            <Button type="primary" onClick={next} block>
              Next
            </Button>
          )}
          {currentStep === 1 && (
            <>
              <Button style={{ marginRight: 8 }} onClick={prev}>
                Previous
              </Button>
              <Button type="primary" onClick={next} block>
                Next
              </Button>
            </>
          )}
          {currentStep === 2 && (
            <>
              <Button style={{ marginRight: 8 }} onClick={prev}>
                Previous
              </Button>
              <Button
                type="default"
                onClick={handleSkipImages}
                style={{ marginRight: 8 }}
              >
                Skip for now...
              </Button>
              <Button type="primary" htmlType="submit">
                Complete Registration
              </Button>
            </>
          )}
        </Form.Item>
      </Form>
    </Card>
  );
}

export default New;
