import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Divider, Select, Breadcrumb, Skeleton } from 'antd';
import { UserOutlined, PhoneOutlined, HomeOutlined, EnvironmentOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import api from '../utils/api';
import { colors, spacing, commonStyles } from '../theme';

const { TextArea } = Input;

function EditCustomer() {
  const navigate = useNavigate();
  const [wordCount, setWordCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [form] = Form.useForm();

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

  const fetchCustomerData = async () => {
    try {
      const response = await api.get('/auth/me');
      const userData = response.data;

      // Fetch house description if exists
      let houseDescription = '';
      try {
        // This would need to be implemented in the API if we want to fetch description
        // For now, we'll leave it empty and let user fill it
      } catch (error) {
        // Description might not exist, that's ok
      }

      // Pre-populate form with user data
      form.setFieldsValue({
        customer_first_name: userData.customer_first_name || '',
        customer_last_name: userData.customer_last_name || '',
        customer_phone_number: userData.customer_phone_number || '',
        customer_address: userData.customer_address || '',
        customer_apt: userData.customer_apt || '',
        customer_town: userData.customer_town || '',
        customer_zip: userData.customer_zip || '',
        customer_home_type: userData.customer_home_type || 0,
        house_description: userData.house_description || ''
      });

      setLoading(false);
    } catch (error) {
      message.error('Failed to load customer data');
      console.error('Error fetching customer data:', error);
      setLoading(false);
    }
  };

  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 onFinish = async (values) => {
    try {
      setLoading(true);

      // Format phone number for backend (remove formatting)
      const formattedData = {
        ...values,
        customer_phone_number: values.customer_phone_number.replace(/\D/g, ''),
        customer_state: 0 // MA is always 0
      };

      await api.put('/auth/update-customer', formattedData);
      message.success('Customer information updated successfully!');
      navigate('/');
    } catch (error) {
      if (error.response) {
        message.error(`Update failed: ${error.response.data?.detail || 'Unknown error'}`);
      } else {
        message.error('Update failed: Network error');
      }
      console.error('Error updating customer:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Card title="Edit Customer Information" style={{ maxWidth: 600, margin: '0 auto', ...commonStyles.cardGray }}>
        <Skeleton active paragraph={{ rows: 10 }} />
      </Card>
    );
  }

  return (
    <div>
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">
            <HomeOutlined /> Home
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>Edit Customer</Breadcrumb.Item>
      </Breadcrumb>
      <Card title="Edit Customer Information" style={{ maxWidth: 600, margin: '0 auto', ...commonStyles.cardGray }}>
      <Form
        name="edit-customer"
        form={form}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
      >
        <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>

        <Form.Item style={{ marginTop: 24 }}>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            block
          >
            Update Information
          </Button>
        </Form.Item>
      </Form>
    </Card>
    </div>
  );
}

export default EditCustomer;
