import { useEffect, useMemo, useState } from 'react';
import axios from 'axios';
import {
  Alert,
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  Result,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import { BulbOutlined, CalculatorOutlined, DeleteOutlined, MailOutlined, ThunderboltOutlined } from '@ant-design/icons';
import { useLocation, useParams } from 'react-router-dom';
import { BASE_URL } from '@/config/serverApiConfig';
import './loadCalculator.css';

const { Title, Text } = Typography;

const APPLIANCE_OPTIONS = [
  { value: 'LED Bulb', label: 'LED Bulb', watts: 10 },
  { value: 'Television', label: 'Television', watts: 120 },
  { value: 'Standing Fan', label: 'Standing Fan', watts: 75 },
  { value: 'Laptop', label: 'Laptop', watts: 65 },
  { value: 'Desktop Computer', label: 'Desktop Computer', watts: 180 },
  { value: 'Router', label: 'Router', watts: 15 },
  { value: 'Refrigerator', label: 'Refrigerator', watts: 180 },
  { value: 'Chest Freezer', label: 'Chest Freezer', watts: 250 },
  { value: 'Air Conditioner', label: 'Air Conditioner', watts: 1200 },
  { value: 'Water Pump', label: 'Water Pump', watts: 750 },
  { value: 'Decoder', label: 'Decoder', watts: 25 },
  { value: 'Microwave', label: 'Microwave', watts: 1200 },
];

const round = (value, precision = 2) => Number(Number(value || 0).toFixed(precision));

export default function LoadCalculatorPage() {
  const { tenantSlug } = useParams();
  const location = useLocation();
  const [tenant, setTenant] = useState(null);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [leadForm] = Form.useForm();
  const [applianceForm] = Form.useForm();
  const [appliances, setAppliances] = useState([]);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      setError('');
      try {
        const response = await axios.get(`${BASE_URL}public/load-calculator/${tenantSlug}`);
        setTenant(response.data?.result?.tenant || null);
      } catch (loadError) {
        setError(loadError.response?.data?.message || 'Unable to load calculator.');
      }
      setLoading(false);
    };

    load();
  }, [tenantSlug]);

  const totals = useMemo(() => {
    const totalPowerWatts = appliances.reduce((sum, item) => sum + Number(item.watts || 0) * Number(item.quantity || 0), 0);
    const totalEnergyWh = appliances.reduce((sum, item) => sum + Number(item.totalWh || 0), 0);
    const recommendedInverterKva = round((totalPowerWatts * 1.25) / 1000, 2);
    const suggestedBatteryKwh = round((totalEnergyWh * 1.2) / 1000, 2);
    const suggestedSolarKw = round((totalEnergyWh / 4.5) / 1000, 2);
    return { totalPowerWatts, totalEnergyWh, recommendedInverterKva, suggestedBatteryKwh, suggestedSolarKw };
  }, [appliances]);

  const attribution = useMemo(() => {
    const params = new URLSearchParams(location.search);
    return {
      utmSource: params.get('utm_source') || '',
      utmMedium: params.get('utm_medium') || '',
      utmCampaign: params.get('utm_campaign') || '',
      utmTerm: params.get('utm_term') || '',
      utmContent: params.get('utm_content') || '',
      referrer: typeof document !== 'undefined' ? document.referrer || '' : '',
      landingPage:
        typeof window !== 'undefined'
          ? `${window.location.origin}${window.location.pathname}${window.location.search}`
          : '',
    };
  }, [location.search]);

  const addAppliance = async () => {
    const values = await applianceForm.validateFields();
    const selected = APPLIANCE_OPTIONS.find((item) => item.value === values.appliance);
    const watts = Number(values.watts || selected?.watts || 0);
    const quantity = Number(values.quantity || 1);
    const hoursPerDay = Number(values.hoursPerDay || 1);
    const totalWh = round(watts * quantity * hoursPerDay, 2);

    setAppliances((current) => [
      ...current,
      {
        key: `${values.appliance}-${Date.now()}`,
        name: values.appliance,
        watts,
        quantity,
        hoursPerDay,
        totalWh,
      },
    ]);

    applianceForm.setFieldsValue({ appliance: undefined, watts: undefined, quantity: 1, hoursPerDay: 1 });
  };

  const removeAppliance = (key) => {
    setAppliances((current) => current.filter((item) => item.key !== key));
  };

  const submitLead = async () => {
    const values = await leadForm.validateFields();
    if (!appliances.length) {
      message.warning('Add at least one appliance before sending the calculation.');
      return;
    }

    setBusy(true);
    setError('');
    try {
      await axios.post(`${BASE_URL}public/load-calculator/${tenantSlug}/submit`, {
        ...values,
        appliances,
        totalPowerWatts: totals.totalPowerWatts,
        totalEnergyWh: totals.totalEnergyWh,
        recommendedInverterKva: totals.recommendedInverterKva,
        suggestedBatteryKwh: totals.suggestedBatteryKwh,
        suggestedSolarKw: totals.suggestedSolarKw,
        source: 'website_load_calculator',
        ...attribution,
      });
      setSubmitted(true);
      message.success('Calculation sent successfully');
    } catch (submitError) {
      setError(submitError.response?.data?.message || 'Unable to send calculation.');
    }
    setBusy(false);
  };

  if (submitted) {
    return (
      <div className="load-calc-page">
        <div className="load-calc-shell">
          <Card className="load-calc-sidecard">
            <Result
              status="success"
              title="Your load calculation has been sent"
              subTitle="A CRM lead has been created with your appliance breakdown, and the team can now follow up with a system recommendation."
            />
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className="load-calc-page">
      <div className="load-calc-shell">
        <div className="load-calc-hero">
          <section className="load-calc-banner">
            <div className="load-calc-brand">
              <CalculatorOutlined />
              <span>{tenant?.name || 'Customer Energy Planning'}</span>
            </div>
            <h1>Solar Load Calculator</h1>
            <p>
              Estimate your daily energy demand, review a practical inverter recommendation, and send the result directly to our CRM so the sales team can respond with the right system design.
            </p>
            <div className="load-calc-note">
              <article>
                <strong>Step 1</strong>
                <span>Add the appliances you want to power.</span>
              </article>
              <article>
                <strong>Step 2</strong>
                <span>See your wattage, daily energy, and system estimate update live.</span>
              </article>
              <article>
                <strong>Step 3</strong>
                <span>Send the result and create a qualified CRM lead automatically.</span>
              </article>
            </div>
          </section>

          <Card className="load-calc-sidecard" loading={loading}>
            <Title level={3} className="load-calc-section-title">
              Your System Snapshot
            </Title>
            <p className="load-calc-section-subtitle">
              This gives a first-pass sizing estimate. Final recommendations may change after site conditions, surge loads, and backup expectations are reviewed.
            </p>
            <div className="load-calc-summary">
              <div className="load-calc-summary-item">
                <strong>Total power</strong>
                <span>{totals.totalPowerWatts} W</span>
              </div>
              <div className="load-calc-summary-item">
                <strong>Daily energy</strong>
                <span>{totals.totalEnergyWh} Wh/day</span>
              </div>
              <div className="load-calc-summary-item">
                <strong>Recommended inverter</strong>
                <span>{totals.recommendedInverterKva} kVA</span>
              </div>
              <div className="load-calc-summary-item">
                <strong>Suggested battery bank</strong>
                <span>{totals.suggestedBatteryKwh} kWh</span>
              </div>
              <div className="load-calc-summary-item">
                <strong>Suggested solar array</strong>
                <span>{totals.suggestedSolarKw} kW</span>
              </div>
            </div>
            <div className="load-calc-recommendation">
              <strong>Recommendation note</strong>
              <Text>
                We use a 25% inverter buffer and a simple energy-production assumption for this estimate. After submission, the CRM lead includes your full appliance breakdown for the sales team.
              </Text>
            </div>
          </Card>
        </div>

        <div className="load-calc-stats">
          <div className="load-calc-stat">
            <span className="load-calc-stat-label">Appliances</span>
            <div className="load-calc-stat-value">{appliances.length}</div>
          </div>
          <div className="load-calc-stat">
            <span className="load-calc-stat-label">Total Wattage</span>
            <div className="load-calc-stat-value">{totals.totalPowerWatts} W</div>
          </div>
          <div className="load-calc-stat">
            <span className="load-calc-stat-label">Daily Energy</span>
            <div className="load-calc-stat-value">{totals.totalEnergyWh} Wh</div>
          </div>
        </div>

        <div className="load-calc-main">
          <Card className="load-calc-sidecard">
            <Title level={3} className="load-calc-section-title">
              Build Your Appliance List
            </Title>
            <p className="load-calc-section-subtitle">
              Choose from common loads, set quantity and usage hours, and refine the wattage if your equipment differs.
            </p>

            {error ? <Alert type="warning" showIcon message={error} style={{ marginBottom: 16 }} /> : null}

            <Form
              form={applianceForm}
              layout="vertical"
              initialValues={{ quantity: 1, hoursPerDay: 1 }}
            >
              <Row gutter={12}>
                <Col xs={24} md={10}>
                  <Form.Item name="appliance" label="Select Appliance" rules={[{ required: true }]}>
                    <Select
                      showSearch
                      options={APPLIANCE_OPTIONS.map((item) => ({ value: item.value, label: `${item.label} (${item.watts}W)` }))}
                      onChange={(value) => {
                        const selected = APPLIANCE_OPTIONS.find((item) => item.value === value);
                        applianceForm.setFieldsValue({ watts: selected?.watts });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col xs={12} md={4}>
                  <Form.Item name="quantity" label="Quantity" rules={[{ required: true }]}>
                    <InputNumber min={1} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={12} md={4}>
                  <Form.Item name="hoursPerDay" label="Hours/Day" rules={[{ required: true }]}>
                    <InputNumber min={0.25} step={0.25} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={6}>
                  <Form.Item name="watts" label="Wattage" rules={[{ required: true }]}>
                    <InputNumber min={1} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>
            </Form>

            <Button type="primary" size="large" icon={<BulbOutlined />} onClick={addAppliance}>
              Add Appliance
            </Button>

            <div style={{ marginTop: 22 }}>
              <Table
                rowKey="key"
                dataSource={appliances}
                pagination={false}
                locale={{
                  emptyText: <div className="load-calc-empty">Your appliance list is empty. Add some appliances to get started.</div>,
                }}
                columns={[
                  { title: 'Appliance', dataIndex: 'name' },
                  { title: 'Qty', dataIndex: 'quantity', width: 70 },
                  { title: 'Watts', dataIndex: 'watts', width: 90, render: (value) => `${value} W` },
                  { title: 'Hours/Day', dataIndex: 'hoursPerDay', width: 110 },
                  { title: 'Total Wh', dataIndex: 'totalWh', width: 120, render: (value) => `${value} Wh` },
                  {
                    title: 'Action',
                    width: 90,
                    render: (_, record) => (
                      <Button size="small" icon={<DeleteOutlined />} onClick={() => removeAppliance(record.key)}>
                        Remove
                      </Button>
                    ),
                  },
                ]}
              />
            </div>
          </Card>

          <Card className="load-calc-sidecard">
            <Title level={3} className="load-calc-section-title">
              Send Your Calculation Request
            </Title>
            <p className="load-calc-section-subtitle">
              Send the result to our team and create a CRM lead with your appliance breakdown, total load, and system estimate.
            </p>

            <Form form={leadForm} layout="vertical" initialValues={{ projectType: 'residential' }}>
              <Form.Item name="name" label="Your Name" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Row gutter={12}>
                <Col xs={24} md={12}>
                  <Form.Item name="email" label="Your Email" rules={[{ required: true }, { type: 'email' }]}>
                    <Input prefix={<MailOutlined />} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="phone" label="Phone Number">
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={12}>
                <Col xs={24} md={12}>
                  <Form.Item name="projectType" label="Project Type" rules={[{ required: true }]}>
                    <Select
                      options={[
                        { value: 'residential', label: 'Residential' },
                        { value: 'commercial', label: 'Commercial' },
                        { value: 'office', label: 'Office' },
                        { value: 'industrial', label: 'Industrial' },
                      ]}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="location" label="Installation Location">
                    <Input placeholder="Abuja, Lagos, Port Harcourt..." />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item name="message" label="Extra Notes">
                <Input.TextArea
                  rows={4}
                  placeholder="Mention backup hours, critical appliances, future expansion, or any site constraints."
                />
              </Form.Item>
            </Form>

            <Space direction="vertical" size={12} style={{ width: '100%' }}>
              <Tag color="green" icon={<ThunderboltOutlined />}>
                Lead source: load calculator
              </Tag>
              {attribution.utmCampaign ? <Tag color="blue">Campaign: {attribution.utmCampaign}</Tag> : null}
              <Button type="primary" size="large" block loading={busy} onClick={submitLead}>
                Send My Calculation
              </Button>
              <Text type="secondary">
                Your calculation is stored with the CRM lead so the team can respond with a more accurate system proposal. Email delivery can also be added when outbound mail is configured.
              </Text>
            </Space>
          </Card>
        </div>
      </div>
    </div>
  );
}
