import { ReloadOutlined } from "@ant-design/icons";
import { Alert, Button, Form, Input, InputNumber, Modal, Radio, Select, Space, Typography } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useEffect, useMemo, useState } from "react";

// Simple customer selector table
function CustomerSelectorTable({ customers, onSelect, isSubmitting }) {
  const [selectedCustNo, setSelectedCustNo] = useState(null);

  const columns = [
    {
      title: "Select",
      key: "select",
      width: 80,
      render: (_, record) => (
        <Radio checked={selectedCustNo === record.custNo} onChange={() => setSelectedCustNo(record.custNo)} />
      )
    },
    { title: "Customer ID", dataIndex: "custNo", key: "custNo" },
    { title: "Name", dataIndex: "name", key: "name" },
    {
      title: "VIN Owner",
      key: "vinOwner",
      render: (_, record) => (record.vinOwner || record.isVehicleOwner ? "Yes" : "No")
    }
  ];

  return (
    <div>
      <ResponsiveTable
        columns={columns}
        mobileColumnKeys={["name", "select", "custNo", "vinOwner"]}
        dataSource={customers}
        rowKey="custNo"
        pagination={false}
        size="small"
      />
      <div style={{ marginTop: 16, display: "flex", gap: 8 }}>
        <Button
          type="primary"
          onClick={() => onSelect(selectedCustNo, false)}
          disabled={!selectedCustNo || isSubmitting}
          loading={isSubmitting}
        >
          Use Selected Customer
        </Button>
        <Button onClick={() => onSelect(null, true)} disabled={isSubmitting} loading={isSubmitting}>
          Create New Customer
        </Button>
      </div>
    </div>
  );
}

/**
 * RR Early RO Creation Form
 * Used from convert button or admin page to create minimal RO before full export
 * @param bodyshop
 * @param socket
 * @param job
 * @param onSuccess - callback when RO is created successfully
 * @param onCancel - callback to close modal
 * @param showCancelButton - whether to show cancel button
 * @returns {JSX.Element}
 * @constructor
 */
export default function RREarlyROForm({ bodyshop, socket, job, onSuccess, onCancel, showCancelButton = true }) {
  const [form] = Form.useForm();

  // Advisors
  const [advisors, setAdvisors] = useState([]);
  const [advLoading, setAdvLoading] = useState(false);

  // Customer selection
  const [customerCandidates, setCustomerCandidates] = useState([]);
  const [showCustomerSelector, setShowCustomerSelector] = useState(false);

  // Loading and success states
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [earlyRoCreated, setEarlyRoCreated] = useState(!!job?.dms_id);
  const [createdRoNumber, setCreatedRoNumber] = useState(job?.dms_id || null);

  // Derive default OpCode parts from bodyshop config (matching dms.container.jsx logic)
  const initialValues = useMemo(() => {
    const cfg = bodyshop?.rr_configuration || {};
    const defaults =
      cfg.opCodeDefault ||
      cfg.op_code_default ||
      cfg.op_codes?.default ||
      cfg.defaults?.opCode ||
      cfg.defaults ||
      cfg.default ||
      {};

    const prefix = defaults.prefix ?? defaults.opCodePrefix ?? "";
    const base = defaults.base ?? defaults.opCodeBase ?? "";
    const suffix = defaults.suffix ?? defaults.opCodeSuffix ?? "";

    return {
      kmin: job?.kmin || 0,
      opPrefix: prefix,
      opBase: base,
      opSuffix: suffix
    };
  }, [bodyshop, job]);

  const getAdvisorNumber = (a) => a?.advisorId;
  const getAdvisorLabel = (a) => `${a?.firstName || ""} ${a?.lastName || ""}`.trim();

  const fetchRrAdvisors = (refresh = false) => {
    if (!socket) return;
    setAdvLoading(true);

    const onResult = (payload) => {
      try {
        const list = payload?.result ?? payload ?? [];
        setAdvisors(Array.isArray(list) ? list : []);
      } finally {
        setAdvLoading(false);
        socket.off("rr-get-advisors:result", onResult);
      }
    };

    socket.once("rr-get-advisors:result", onResult);
    socket.emit("rr-get-advisors", { departmentType: "B", refresh }, (ack) => {
      if (ack?.ok) {
        const list = ack.result ?? [];
        setAdvisors(Array.isArray(list) ? list : []);
      } else if (ack) {
        console.error("Error fetching RR Advisors:", ack.error);
      }
      setAdvLoading(false);
      socket.off("rr-get-advisors:result", onResult);
    });
  };

  useEffect(() => {
    fetchRrAdvisors(false);
  }, [bodyshop?.id, socket]);

  const handleStartEarlyRO = async (values) => {
    if (!socket) {
      console.error("Socket not available");
      return;
    }

    setIsSubmitting(true);

    const txEnvelope = {
      advisorNo: values.advisorNo,
      story: values.story || "",
      kmin: values.kmin || job?.kmin || 0,
      opPrefix: values.opPrefix || "",
      opBase: values.opBase || "",
      opSuffix: values.opSuffix || ""
    };

    // Emit the early RO creation request
    socket.emit("rr-create-early-ro", {
      jobId: job.id,
      txEnvelope
    });

    // Wait for customer selection
    const customerListener = (candidates) => {
      console.log("Received rr-select-customer event with candidates:", candidates);
      setCustomerCandidates(candidates || []);
      setShowCustomerSelector(true);
      setIsSubmitting(false);
      socket.off("rr-select-customer", customerListener);
    };

    socket.once("rr-select-customer", customerListener);

    // Handle failures
    const failureListener = (payload) => {
      if (payload?.jobId === job.id) {
        console.error("Early RO creation failed:", payload.error);
        alert(`Failed to create early RO: ${payload.error}`);
        setIsSubmitting(false);
        setShowCustomerSelector(false);
        socket.off("export-failed", failureListener);
        socket.off("rr-select-customer", customerListener);
      }
    };

    socket.once("export-failed", failureListener);
  };

  const handleCustomerSelected = (custNo, createNew = false) => {
    if (!socket) return;

    console.log("handleCustomerSelected called:", { custNo, createNew, custNoType: typeof custNo });

    setIsSubmitting(true);
    setShowCustomerSelector(false);

    const payload = {
      jobId: job.id,
      custNo: createNew ? null : custNo,
      create: createNew
    };

    console.log("Emitting rr-early-customer-selected:", payload);

    // Emit customer selection
    socket.emit("rr-early-customer-selected", payload, (ack) => {
      console.log("Received ack from rr-early-customer-selected:", ack);
      setIsSubmitting(false);

      if (ack?.ok) {
        const roNumber = ack.dmsRoNo || ack.outsdRoNo;
        setEarlyRoCreated(true);
        setCreatedRoNumber(roNumber);
        onSuccess?.({ roNumber, ...ack });
      } else {
        alert(`Failed to create early RO: ${ack?.error || "Unknown error"}`);
      }
    });

    // Also listen for socket events
    const successListener = (payload) => {
      if (payload?.jobId === job.id) {
        const roNumber = payload.dmsRoNo || payload.outsdRoNo;
        console.log("Early RO created:", roNumber);
        socket.off("rr-early-ro-created", successListener);
        socket.off("export-failed", failureListener);
      }
    };

    const failureListener = (payload) => {
      if (payload?.jobId === job.id) {
        console.error("Early RO creation failed:", payload.error);
        setIsSubmitting(false);
        setEarlyRoCreated(false);
        socket.off("rr-early-ro-created", successListener);
        socket.off("export-failed", failureListener);
      }
    };

    socket.once("rr-early-ro-created", successListener);
    socket.once("export-failed", failureListener);
  };

  // If early RO already created, show success message
  if (earlyRoCreated) {
    return (
      <Alert
        title="Early Reynolds RO Created"
        description={`RO Number: ${createdRoNumber || "N/A"} - You can now convert the job.`}
        type="success"
        showIcon
        style={{ marginBottom: 16 }}
      />
    );
  }

  // If showing customer selector, render modal
  if (showCustomerSelector) {
    return (
      <>
        <Typography.Title level={5}>Create Early Reynolds RO</Typography.Title>
        <Typography.Paragraph type="secondary">Waiting for customer selection...</Typography.Paragraph>

        <Modal
          title="Select Customer for Early RO"
          open={true}
          width={800}
          footer={null}
          onCancel={() => {
            setShowCustomerSelector(false);
            setIsSubmitting(false);
          }}
        >
          <CustomerSelectorTable
            customers={customerCandidates}
            onSelect={handleCustomerSelected}
            isSubmitting={isSubmitting}
          />
        </Modal>
      </>
    );
  }

  // Handle manual submit (since we can't nest forms)
  const handleManualSubmit = async () => {
    try {
      const values = await form.validateFields();
      handleStartEarlyRO(values);
    } catch (error) {
      console.error("Validation failed:", error);
    }
  };

  // Show the form
  return (
    <div style={{ marginTop: 16 }}>
      <Typography.Title level={5}>Create Early Reynolds RO</Typography.Title>
      <Typography.Paragraph type="secondary" style={{ fontSize: "12px" }}>
        Complete this section to create a minimal RO in Reynolds before converting the job.
      </Typography.Paragraph>

      <Form form={form} layout="vertical" component={false} initialValues={initialValues}>
        <Form.Item name="advisorNo" label="Advisor" rules={[{ required: true, message: "Please select an advisor" }]}>
          <Select
            showSearch={{
              optionFilterProp: "children",
              filterOption: (input, option) => (option?.children?.toLowerCase() ?? "").includes(input.toLowerCase())
            }}
            loading={advLoading}
            placeholder="Select advisor..."
            popupRender={(menu) => (
              <>
                {menu}
                <Button
                  type="link"
                  icon={<ReloadOutlined />}
                  onClick={() => fetchRrAdvisors(true)}
                  style={{ width: "100%", textAlign: "left" }}
                >
                  Refresh Advisors
                </Button>
              </>
            )}
          >
            {advisors.map((adv) => (
              <Select.Option key={getAdvisorNumber(adv)} value={getAdvisorNumber(adv)}>
                {getAdvisorLabel(adv)}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="kmin"
          label="Mileage In"
          rules={[
            { required: true, message: "Please enter initial mileage" },
            { type: "number", min: 1, message: "Mileage must be greater than 0" }
          ]}
        >
          <InputNumber min={1} style={{ width: "100%" }} />
        </Form.Item>

        {/* RR OpCode (prefix / base / suffix) */}
        <Form.Item required label="RR OpCode">
          <Space.Compact block>
            <Form.Item name="opPrefix" noStyle>
              <Input allowClear maxLength={4} style={{ width: "30%" }} placeholder="Prefix" />
            </Form.Item>
            <Form.Item name="opBase" noStyle rules={[{ required: true, message: "Base Required" }]}>
              <Input allowClear maxLength={10} style={{ width: "40%" }} placeholder="Base" />
            </Form.Item>
            <Form.Item name="opSuffix" noStyle>
              <Input allowClear maxLength={4} style={{ width: "30%" }} placeholder="Suffix" />
            </Form.Item>
          </Space.Compact>
        </Form.Item>

        <Form.Item name="story" label="Comments / Story (Optional)">
          <Input.TextArea rows={2} maxLength={240} showCount placeholder="Enter comments or story..." />
        </Form.Item>

        <div style={{ marginTop: 16 }}>
          <Space>
            <Button type="primary" onClick={handleManualSubmit} loading={isSubmitting} disabled={advLoading}>
              Create Early RO
            </Button>
            {showCancelButton && <Button onClick={onCancel}>Cancel</Button>}
          </Space>
        </div>
      </Form>
    </div>
  );
}
