import { useState, useMemo, useEffect, useCallback } from 'react';
import { Button, Table, Input, Tabs, Modal, Form, InputNumber, Select, Typography, Breadcrumb, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from '../router/routes.constant';

interface PalletconfigResponse {
  submenu_id: number;
  cases_per_pallet: number | null;
  notes: string | null;
  metadata: Record<string, unknown> | null;
  id: string;
  version: number;
  deleted_at: string | null;
  created_at: string;
  updated_at: string;
}

interface PalletconfighistoryResponse {
  submenu_id: number;
  pallet_config_id: string | null;
  change_date: string;
  change_description: string | null;
  changed_by: number | null;
  change_type: string;
  id: string;
  created_at: string;
  updated_at: string;
}

interface PalletMetadata {
  name?: string;
  length?: number;
  width?: number;
  height?: number;
  max_weight?: number;
  material_type?: string;
  description?: string;
}

export default function PalletConfigsPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const [palletConfigs, setPalletConfigs] = useState<PalletconfigResponse[]>([]);
  const [palletConfigHistory, setPalletConfigHistory] = useState<PalletconfighistoryResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [historyLoading, setHistoryLoading] = useState<boolean>(false);
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [selectedConfigId, setSelectedConfigId] = useState<string | null>(null);
  const [searchText, setSearchText] = useState<string>('');
  const [activeTab, setActiveTab] = useState<string>('configurations');

  const filteredConfigs = useMemo(() => {
    return palletConfigs.filter(c => 
      !searchText || JSON.stringify(c).toLowerCase().includes(searchText.toLowerCase())
    );
  }, [palletConfigs, searchText]);

  const fetchConfigs = useCallback(async () => {
    setLoading(true);
    try {
      const result = await request<PalletconfigResponse[]>({
        method: 'GET',
        path: '/pallet-configs/',
        query: { limit: 50, offset: 0 }
      });
      setPalletConfigs(result.data);
    } catch (error) {
      messageApi.error('Failed to load pallet configurations');
    } finally {
      setLoading(false);
    }
  }, [messageApi]);

  const fetchHistory = useCallback(async () => {
    setHistoryLoading(true);
    try {
      const result = await request<PalletconfighistoryResponse[]>({
        method: 'GET',
        path: '/pallet-configs/history',
        query: { limit: 50, offset: 0 }
      });
      setPalletConfigHistory(result.data);
    } catch (error) {
      messageApi.error('Failed to load history');
    } finally {
      setHistoryLoading(false);
    }
  }, [messageApi]);

  useEffect(() => {
    fetchConfigs();
    fetchHistory();
  }, [fetchConfigs, fetchHistory]);

  const openCreateModal = useCallback(() => {
    setCreateModalVisible(true);
  }, []);

  const closeCreateModal = useCallback(() => {
    setCreateModalVisible(false);
    createForm.resetFields();
  }, [createForm]);

  const openEditModal = useCallback((record: PalletconfigResponse) => {
    setEditModalVisible(true);
    setSelectedConfigId(record.id);
    const metadata = (record.metadata as PalletMetadata) || {};
    editForm.setFieldsValue({
      name: metadata.name,
      cases_per_pallet: record.cases_per_pallet,
      length: metadata.length,
      width: metadata.width,
      height: metadata.height,
      max_weight: metadata.max_weight,
      material_type: metadata.material_type,
      description: metadata.description,
      notes: record.notes
    });
  }, [editForm]);

  const closeEditModal = useCallback(() => {
    setEditModalVisible(false);
    setSelectedConfigId(null);
    editForm.resetFields();
  }, [editForm]);

  const handleCreateSubmit = useCallback(async () => {
    try {
      const formValues = await createForm.validateFields();
      await request<PalletconfigResponse>({
        method: 'POST',
        path: '/pallet-configs/',
        body: {
          submenu_id: formValues.submenu_id || 1,
          cases_per_pallet: formValues.cases_per_pallet,
          notes: formValues.notes,
          metadata: {
            name: formValues.name,
            length: formValues.length,
            width: formValues.width,
            height: formValues.height,
            max_weight: formValues.max_weight,
            material_type: formValues.material_type,
            description: formValues.description
          }
        }
      });
      messageApi.success('Pallet configuration created successfully');
      setCreateModalVisible(false);
      createForm.resetFields();
      fetchConfigs();
      fetchHistory();
    } catch (error) {
      messageApi.error('Failed to create pallet configuration');
    }
  }, [createForm, messageApi, fetchConfigs, fetchHistory]);

  const handleEditSubmit = useCallback(async () => {
    if (!selectedConfigId) return;
    try {
      const formValues = await editForm.validateFields();
      await request<PalletconfigResponse>({
        method: 'PUT',
        path: '/pallet-configs/{entity_id}',
        pathParams: { entity_id: selectedConfigId },
        body: {
          cases_per_pallet: formValues.cases_per_pallet,
          notes: formValues.notes,
          metadata: {
            name: formValues.name,
            length: formValues.length,
            width: formValues.width,
            height: formValues.height,
            max_weight: formValues.max_weight,
            material_type: formValues.material_type,
            description: formValues.description
          }
        }
      });
      messageApi.success('Pallet configuration updated successfully');
      setEditModalVisible(false);
      setSelectedConfigId(null);
      editForm.resetFields();
      fetchConfigs();
      fetchHistory();
    } catch (error) {
      messageApi.error('Failed to update pallet configuration');
    }
  }, [selectedConfigId, editForm, messageApi, fetchConfigs, fetchHistory]);

  const handleDelete = useCallback((record: PalletconfigResponse) => {
    Modal.confirm({
      title: 'Delete Pallet Configuration',
      content: 'Are you sure you want to delete this configuration?',
      okText: 'Delete',
      okType: 'danger',
      cancelText: 'Cancel',
      onOk: async () => {
        try {
          await request({
            method: 'DELETE',
            path: '/pallet-configs/{entity_id}',
            pathParams: { entity_id: record.id }
          });
          messageApi.success('Pallet configuration deleted successfully');
          fetchConfigs();
          fetchHistory();
        } catch (error) {
          messageApi.error('Failed to delete pallet configuration');
        }
      }
    });
  }, [messageApi, fetchConfigs, fetchHistory]);

  const navigateToDashboard = useCallback(() => {
    navigate(ROUTES.DASHBOARD || '/');
  }, [navigate]);

  const navigateToConfiguration = useCallback(() => {
    navigate(ROUTES.CONFIGURATION || '/configuration');
  }, [navigate]);

  const configColumns = useMemo(() => [
    {
      title: 'Config ID',
      dataIndex: 'id',
      key: 'id',
      width: 120
    },
    {
      title: 'Cases Per Pallet',
      dataIndex: 'cases_per_pallet',
      key: 'cases_per_pallet'
    },
    {
      title: 'Notes',
      dataIndex: 'notes',
      key: 'notes',
      ellipsis: true
    },
    {
      title: 'Version',
      dataIndex: 'version',
      key: 'version',
      width: 80
    },
    {
      title: 'Created At',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => new Date(text).toLocaleString()
    },
    {
      title: 'Updated At',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (text: string) => new Date(text).toLocaleString()
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 180,
      render: (_: unknown, record: PalletconfigResponse) => (
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            Edit
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            Delete
          </Button>
        </div>
      )
    }
  ], [openEditModal, handleDelete]);

  const historyColumns = useMemo(() => [
    {
      title: 'History ID',
      dataIndex: 'id',
      key: 'id',
      width: 120
    },
    {
      title: 'Config ID',
      dataIndex: 'pallet_config_id',
      key: 'pallet_config_id'
    },
    {
      title: 'Change Type',
      dataIndex: 'change_type',
      key: 'change_type',
      width: 120
    },
    {
      title: 'Change Description',
      dataIndex: 'change_description',
      key: 'change_description',
      ellipsis: true
    },
    {
      title: 'Changed By',
      dataIndex: 'changed_by',
      key: 'changed_by',
      width: 100
    },
    {
      title: 'Change Date',
      dataIndex: 'change_date',
      key: 'change_date',
      render: (text: string) => new Date(text).toLocaleString()
    }
  ], []);

  const tabItems = useMemo(() => [
    {
      key: 'configurations',
      label: 'Configurations',
      children: (
        <Table
          columns={configColumns}
          dataSource={filteredConfigs}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true
          }}
        />
      )
    },
    {
      key: 'history',
      label: 'Change History',
      children: (
        <Table
          columns={historyColumns}
          dataSource={palletConfigHistory}
          rowKey="id"
          loading={historyLoading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true
          }}
        />
      )
    }
  ], [configColumns, filteredConfigs, loading, historyColumns, palletConfigHistory, historyLoading]);

  return (
    <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column', padding: '24px', background: '#f5f5f5' }}>
      {contextHolder}
      <Breadcrumb
        style={{ marginBottom: '16px' }}
        items={[
          { title: 'Dashboard', onClick: navigateToDashboard },
          { title: 'Configuration', onClick: navigateToConfiguration },
          { title: 'Pallet Configurations' }
        ]}
      />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <Typography.Title level={2} style={{ margin: 0 }}>
          Pallet Configurations
        </Typography.Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={openCreateModal}>
          Create Configuration
        </Button>
      </div>
      <div style={{ display: 'flex', gap: '12px', marginBottom: '16px', flexWrap: 'wrap' }}>
        <Input.Search
          placeholder="Search by name..."
          allowClear
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ width: '300px' }}
        />
      </div>
      <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
      <Modal
        title="Create Pallet Configuration"
        open={createModalVisible}
        onOk={handleCreateSubmit}
        onCancel={closeCreateModal}
        okText="Create"
        cancelText="Cancel"
        width={640}
      >
        <Form form={createForm} layout="vertical">
          <Form.Item
            label="Name"
            name="name"
            rules={[{ required: true, message: 'Please enter configuration name' }]}
          >
            <Input placeholder="Enter configuration name" />
          </Form.Item>
          <Form.Item
            label="Cases Per Pallet"
            name="cases_per_pallet"
            rules={[{ required: true, message: 'Please enter cases per pallet' }]}
          >
            <InputNumber placeholder="Enter cases per pallet" min={1} style={{ width: '100%' }} />
          </Form.Item>
          <div style={{ display: 'flex', gap: '12px' }}>
            <Form.Item
              label="Length"
              name="length"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <InputNumber placeholder="L" min={0} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
              label="Width"
              name="width"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <InputNumber placeholder="W" min={0} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
              label="Height"
              name="height"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <InputNumber placeholder="H" min={0} style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <Form.Item
            label="Max Weight (kg)"
            name="max_weight"
            rules={[{ required: true, message: 'Please enter max weight' }]}
          >
            <InputNumber placeholder="Enter max weight" min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="Material Type"
            name="material_type"
            rules={[{ required: true, message: 'Please select material type' }]}
          >
            <Select
              placeholder="Select material type"
              options={[
                { label: 'Wood', value: 'wood' },
                { label: 'Plastic', value: 'plastic' },
                { label: 'Metal', value: 'metal' },
                { label: 'Composite', value: 'composite' }
              ]}
            />
          </Form.Item>
          <Form.Item label="Description" name="description">
            <Input.TextArea placeholder="Enter description" rows={3} />
          </Form.Item>
          <Form.Item label="Notes" name="notes">
            <Input.TextArea placeholder="Enter notes" rows={2} />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="Edit Pallet Configuration"
        open={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={closeEditModal}
        okText="Save"
        cancelText="Cancel"
        width={640}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item
            label="Name"
            name="name"
            rules={[{ required: true, message: 'Please enter configuration name' }]}
          >
            <Input placeholder="Enter configuration name" />
          </Form.Item>
          <Form.Item
            label="Cases Per Pallet"
            name="cases_per_pallet"
            rules={[{ required: true, message: 'Please enter cases per pallet' }]}
          >
            <InputNumber placeholder="Enter cases per pallet" min={1} style={{ width: '100%' }} />
          </Form.Item>
          <div style={{ display: 'flex', gap: '12px' }}>
            <Form.Item
              label="Length"
              name="length"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <InputNumber placeholder="L" min={0} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
              label="Width"
              name="width"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <InputNumber placeholder="W" min={0} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
              label="Height"
              name="height"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <InputNumber placeholder="H" min={0} style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <Form.Item
            label="Max Weight (kg)"
            name="max_weight"
            rules={[{ required: true, message: 'Please enter max weight' }]}
          >
            <InputNumber placeholder="Enter max weight" min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="Material Type"
            name="material_type"
            rules={[{ required: true, message: 'Please select material type' }]}
          >
            <Select
              placeholder="Select material type"
              options={[
                { label: 'Wood', value: 'wood' },
                { label: 'Plastic', value: 'plastic' },
                { label: 'Metal', value: 'metal' },
                { label: 'Composite', value: 'composite' }
              ]}
            />
          </Form.Item>
          <Form.Item label="Description" name="description">
            <Input.TextArea placeholder="Enter description" rows={3} />
          </Form.Item>
          <Form.Item label="Notes" name="notes">
            <Input.TextArea placeholder="Enter notes" rows={2} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}