import { useEffect, useMemo, useState } from 'react';
import {
  Alert,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import { CopyOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { request } from '@/request';
import { WorkflowPage } from './shared';
import { BASE_URL } from '@/config/serverApiConfig';
import { buildFormBuilderPublicEndpoint } from './publicForms';

const { Text } = Typography;

const FIELD_TYPES = ['text', 'textarea', 'number', 'select', 'checkbox', 'date', 'email', 'phone'].map((value) => ({
  value,
  label: value,
}));

const TARGET_OPTIONS = [
  { value: 'lead', label: 'Lead' },
  { value: 'contact', label: 'Contact' },
  { value: 'client', label: 'Customer' },
];

export default function FormBuilderWorkbench() {
  const [definitions, setDefinitions] = useState([]);
  const [submissions, setSubmissions] = useState([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const load = async () => {
    setLoading(true);
    const [defRes, subRes] = await Promise.all([
      request.get({ entity: 'form-builder/definitions' }),
      request.get({ entity: 'form-builder/submissions' }),
    ]);
    setDefinitions(defRes?.result || []);
    setSubmissions(subRes?.result || []);
    setLoading(false);
  };

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

  const fieldRows = Form.useWatch('fields', form) || [];

  const save = async () => {
    const values = await form.validateFields();
    const response = await request.post({ entity: 'form-builder/definition', jsonData: values });
    if (response?.success) {
      message.success('Form definition created');
      setOpen(false);
      form.resetFields();
      load();
    }
  };

  const typeSummary = useMemo(
    () => ({
      total: definitions.length,
      public: definitions.filter((item) => item.type === 'public').length,
      internal: definitions.filter((item) => item.type !== 'public').length,
    }),
    [definitions]
  );

  const copyPublicEndpoint = async (slug) => {
    const endpoint = buildFormBuilderPublicEndpoint(BASE_URL, slug);
    await navigator.clipboard.writeText(endpoint);
    message.success('Public submit endpoint copied');
  };

  return (
    <WorkflowPage
      title="Form Builder"
      description="Design internal and public forms from one shared schema, route submissions into CRM entities, and review collected responses."
      permission="platform.form-builder.read"
      extra={
        <Space>
          <Button icon={<ReloadOutlined />} onClick={load}>
            Refresh
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setOpen(true)}>
            New Form
          </Button>
        </Space>
      }
    >
      <Space direction="vertical" size={16} style={{ width: '100%' }}>
        <Alert
          type="info"
          showIcon
          message="Use public forms for hosted lead capture and internal forms for structured staff intake without raw JSON editing."
        />

        <Row gutter={[16, 16]}>
          <Col xs={24} md={8}>
            <Card><Text strong>Total forms:</Text> {typeSummary.total}</Card>
          </Col>
          <Col xs={24} md={8}>
            <Card><Text strong>Public:</Text> {typeSummary.public}</Card>
          </Col>
          <Col xs={24} md={8}>
            <Card><Text strong>Internal:</Text> {typeSummary.internal}</Card>
          </Col>
        </Row>

        <Card title="Definitions">
          <Table
            rowKey="_id"
            dataSource={definitions}
            loading={loading}
            pagination={false}
            columns={[
              { title: 'Name', dataIndex: 'name' },
              { title: 'Slug', dataIndex: 'slug' },
              { title: 'Type', dataIndex: 'type', render: (value) => <Tag color={value === 'public' ? 'blue' : 'purple'}>{value}</Tag> },
              { title: 'Target', dataIndex: 'targetEntity' },
              {
                title: 'Fields',
                render: (_, record) => (record.fields || []).map((field) => field.label || field.key).join(', ') || '-',
              },
              { title: 'Status', dataIndex: 'status', render: (value) => <Tag>{value}</Tag> },
              {
                title: 'Website Endpoint',
                render: (_, record) =>
                  record.type === 'public' && record.status === 'published' ? (
                    <Button size="small" icon={<CopyOutlined />} onClick={() => copyPublicEndpoint(record.slug)}>
                      Copy Endpoint
                    </Button>
                  ) : (
                    <Text type="secondary">Publish to enable</Text>
                  ),
              },
            ]}
          />
        </Card>

        <Card title="Website Integration">
          <Space direction="vertical" size={10} style={{ width: '100%' }}>
            <Text>
              Published public form-builder forms now create CRM leads, contacts, or customers automatically.
            </Text>
            <Text type="secondary">
              Your external website can submit directly to the public endpoint shown above. Required fields are validated from the form definition before a CRM record is created.
            </Text>
            <Divider style={{ margin: '4px 0' }} />
            <Text code>{`${BASE_URL}public/builder-forms/:slug/submit`}</Text>
          </Space>
        </Card>

        <Card title="Recent Submissions">
          <Table
            rowKey="_id"
            dataSource={submissions}
            pagination={false}
            columns={[
              { title: 'Target', dataIndex: 'targetEntity' },
              { title: 'Source', dataIndex: 'source' },
              {
                title: 'Payload',
                render: (_, record) => (
                  <Text type="secondary">
                    {Object.entries(record.payload || {})
                      .slice(0, 3)
                      .map(([key, value]) => `${key}: ${value}`)
                      .join(', ') || '-'}
                  </Text>
                ),
              },
              { title: 'Submitted', dataIndex: 'submittedAt', render: (value) => (value ? new Date(value).toLocaleString() : '-') },
            ]}
          />
        </Card>
      </Space>

      <Modal title="Create Form Definition" open={open} onCancel={() => setOpen(false)} onOk={save} width={880}>
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: 'internal',
            targetEntity: 'lead',
            status: 'draft',
            fields: [{ key: 'fullName', label: 'Full Name', type: 'text', required: true }],
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="Name" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="slug" label="Slug" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="type" label="Form Type" rules={[{ required: true }]}>
                <Select options={[{ value: 'internal', label: 'Internal' }, { value: 'public', label: 'Public' }]} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="targetEntity" label="Target Entity" rules={[{ required: true }]}>
                <Select options={TARGET_OPTIONS} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="status" label="Status" rules={[{ required: true }]}>
                <Select options={[{ value: 'draft', label: 'Draft' }, { value: 'published', label: 'Published' }]} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={2} />
          </Form.Item>

          <Form.List name="fields">
            {(fields, { add, remove }) => (
              <Space direction="vertical" size={12} style={{ width: '100%' }}>
                {fields.map((field, index) => (
                  <Card
                    key={field.key}
                    size="small"
                    title={`Field ${index + 1}`}
                    extra={
                      fields.length > 1 ? (
                        <Button type="link" danger onClick={() => remove(field.name)}>
                          Remove
                        </Button>
                      ) : null
                    }
                  >
                    <Row gutter={12}>
                      <Col span={8}>
                        <Form.Item name={[field.name, 'key']} label="Key" rules={[{ required: true }]}>
                          <Input />
                        </Form.Item>
                      </Col>
                      <Col span={8}>
                        <Form.Item name={[field.name, 'label']} label="Label" rules={[{ required: true }]}>
                          <Input />
                        </Form.Item>
                      </Col>
                      <Col span={8}>
                        <Form.Item name={[field.name, 'type']} label="Field Type" rules={[{ required: true }]}>
                          <Select options={FIELD_TYPES} />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={12}>
                      <Col span={16}>
                        <Form.Item name={[field.name, 'placeholder']} label="Placeholder">
                          <Input />
                        </Form.Item>
                      </Col>
                      <Col span={8}>
                        <Form.Item name={[field.name, 'required']} label="Required">
                          <Select options={[{ value: true, label: 'Yes' }, { value: false, label: 'No' }]} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Card>
                ))}
                <Button onClick={() => add({ type: 'text', required: false })}>Add Field</Button>
              </Space>
            )}
          </Form.List>

          <Form.Item name="successMessage" label="Success Message">
            <Input />
          </Form.Item>
        </Form>

        <Alert
          style={{ marginTop: 16 }}
          type="success"
          showIcon
          message={`This form currently has ${fieldRows.length} field${fieldRows.length === 1 ? '' : 's'}.`}
        />
      </Modal>
    </WorkflowPage>
  );
}
