import React, { memo, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Col, Row, Space, Input, ConfigProvider, Card, Tag, Spin, Table, Modal } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, EyeOutlined } from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { Typography } from 'antd';

const { Text, Title } = Typography;

// Mock data untuk sparepart
const mockSpareparts = [
  {
    sparepart_id: 1,
    sparepart_name: 'Compressor Oil',
    sparepart_code: 'SP-COMP-001',
    sparepart_description: 'Oil for industrial compressor maintenance',
    brand_name: 'Sullair',
    model: '750H',
    type: 'consumable',
    is_active: true,
    created_date: '2024-01-15',
    updated_date: '2024-11-20'
  },
  {
    sparepart_id: 2,
    sparepart_name: 'Air Filter Element',
    sparepart_code: 'SP-AF-002',
    sparepart_description: 'High efficiency air filter for compressor',
    brand_name: 'Ingersoll Rand',
    model: 'X7',
    type: 'filter',
    is_active: true,
    created_date: '2024-02-20',
    updated_date: '2024-10-15'
  },
  {
    sparepart_id: 3,
    sparepart_name: 'Oil Filter',
    sparepart_code: 'SP-OF-003',
    sparepart_description: 'Oil filtration system component',
    brand_name: 'Atlas Copco',
    model: 'GA 55',
    type: 'filter',
    is_active: false,
    created_date: '2024-03-10',
    updated_date: '2024-09-05'
  },
  {
    sparepart_id: 4,
    sparepart_name: 'Cooling Fan Motor',
    sparepart_code: 'SP-CFM-004',
    sparepart_description: 'Motor for cooling system in compressor',
    brand_name: 'Kobelco',
    model: 'SRE-110',
    type: 'electrical',
    is_active: true,
    created_date: '2024-04-05',
    updated_date: '2024-11-10'
  },
  {
    sparepart_id: 5,
    sparepart_name: 'Coupling Elastomer',
    sparepart_code: 'SP-CE-005',
    sparepart_description: 'Elastomer coupling for drive system',
    brand_name: 'Kaesar',
    model: 'Comprex',
    type: 'mechanical',
    is_active: true,
    created_date: '2024-05-12',
    updated_date: '2024-11-18'
  }
];

const IndexSparepart = memo(function IndexSparepart() {
  const navigate = useNavigate();
  const { setBreadcrumbItems } = useBreadcrumb();
  const [spareparts, setSpareparts] = useState([]);
  const [filteredSpareparts, setFilteredSpareparts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchValue, setSearchValue] = useState('');

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      // Simulasi loading data
      setTimeout(() => {
        setSpareparts(mockSpareparts);
        setFilteredSpareparts(mockSpareparts);
        setLoading(false);
      }, 1000);

      setBreadcrumbItems([
        { title: <Text strong style={{ fontSize: '14px' }}>• Master</Text> },
        { title: <Text strong style={{ fontSize: '14px' }}>Sparepart</Text> }
      ]);
    } else {
      navigate('/signin');
    }
  }, [navigate, setBreadcrumbItems]);

  // Fungsi untuk pencarian
  const handleSearch = (value) => {
    if (!value) {
      setFilteredSpareparts(spareparts);
    } else {
      const filtered = spareparts.filter(item =>
        item.sparepart_name.toLowerCase().includes(value.toLowerCase()) ||
        item.sparepart_code.toLowerCase().includes(value.toLowerCase()) ||
        item.brand_name.toLowerCase().includes(value.toLowerCase()) ||
        item.model.toLowerCase().includes(value.toLowerCase())
      );
      setFilteredSpareparts(filtered);
    }
  };

  const handleSearchChange = (e) => {
    const value = e.target.value;
    setSearchValue(value);
    handleSearch(value);
  };

  const handleSearchClear = () => {
    setSearchValue('');
    setFilteredSpareparts(spareparts);
  };

  const handleAddSparepart = () => {
    // Navigasi ke halaman tambah sparepart (akan dibuat nanti)
    NotifAlert({
      icon: 'info',
      title: 'Info',
      message: 'Fitur tambah sparepart akan segera dibuat',
    });
  };

  const handleEditSparepart = (record) => {
    // Navigasi ke halaman edit sparepart (akan dibuat nanti)
    NotifAlert({
      icon: 'info',
      title: 'Info',
      message: `Edit sparepart: ${record.sparepart_name}`,
    });
  };

  const handleViewSparepart = (record) => {
    // Tampilkan detail sparepart (akan dibuat nanti)
    NotifOk({
      icon: 'success',
      title: 'Info',
      message: `View sparepart: ${record.sparepart_name}`,
    });
  };

  const handleDeleteSparepart = (record) => {
    NotifConfirmDialog({
      icon: 'question',
      title: 'Konfirmasi',
      message: 'Apakah anda yakin hapus sparepart "' + record.sparepart_name + '" ?',
      onConfirm: () => {
        const updatedSpareparts = spareparts.filter(item => item.sparepart_id !== record.sparepart_id);
        setSpareparts(updatedSpareparts);
        setFilteredSpareparts(updatedSpareparts);
        NotifOk({
          icon: 'success',
          title: 'Berhasil',
          message: `Sparepart ${record.sparepart_name} deleted successfully.`,
        });
      },
      onCancel: () => {},
    });
  };

  // Kolom-kolom tabel
  const columns = [
    {
      title: 'No',
      key: 'no',
      width: '5%',
      align: 'center',
      render: (_, __, index) => index + 1,
    },
    {
      title: 'Sparepart Code',
      dataIndex: 'sparepart_code',
      key: 'sparepart_code',
      width: '15%',
    },
    {
      title: 'Sparepart Name',
      dataIndex: 'sparepart_name',
      key: 'sparepart_name',
      width: '20%',
    },
    {
      title: 'Description',
      dataIndex: 'sparepart_description',
      key: 'sparepart_description',
      width: '20%',
      render: (text) => text || '-',
    },
    {
      title: 'Brand',
      dataIndex: 'brand_name',
      key: 'brand_name',
      width: '12%',
    },
    {
      title: 'Model',
      dataIndex: 'model',
      key: 'model',
      width: '10%',
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: '10%',
      render: (text) => (
        <Tag color={
          text === 'consumable' ? 'blue' : 
          text === 'filter' ? 'green' : 
          text === 'electrical' ? 'orange' : 
          'default'
        }>
          {text?.toUpperCase()}
        </Tag>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'is_active',
      key: 'is_active',
      width: '8%',
      align: 'center',
      render: (_, { is_active }) => (
        <>
          {is_active === true ? (
            <Tag color={'green'} key={'status'}>
              Active
            </Tag>
          ) : (
            <Tag color={'red'} key={'status'}>
              Inactive
            </Tag>
          )}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      align: 'center',
      width: '15%',
      render: (_, record) => (
        <Space>
          <Button
            icon={<EyeOutlined />}
            onClick={() => handleViewSparepart(record)}
            style={{
              color: '#1890ff',
              borderColor: '#1890ff',
            }}
            size="small"
          />
          <Button
            icon={<EditOutlined />}
            onClick={() => handleEditSparepart(record)}
            style={{
              color: '#faad14',
              borderColor: '#faad14',
            }}
            size="small"
          />
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteSparepart(record)}
            style={{
              borderColor: '#ff4d4f',
            }}
            size="small"
          />
        </Space>
      ),
    },
  ];

  return (
    <React.Fragment>
      <Card>
        <Row>
          <Col xs={24}>
            <Row justify="space-between" align="middle" gutter={[8, 8]}>
              <Col xs={24} sm={24} md={12} lg={12}>
                <Input.Search
                  placeholder="Search sparepart..."
                  value={searchValue}
                  onChange={handleSearchChange}
                  onSearch={handleSearch}
                  allowClear={{
                    clearIcon: <span onClick={handleSearchClear}>✕</span>,
                  }}
                  enterButton={
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      style={{
                        backgroundColor: '#23A55A',
                        borderColor: '#23A55A',
                      }}
                    >
                      Search
                    </Button>
                  }
                  size="large"
                />
              </Col>
              <Col>
                <Space wrap size="small">
                  <ConfigProvider
                    theme={{
                      token: { colorBgContainer: '#E9F6EF' },
                      components: {
                        Button: {
                          defaultBg: 'white',
                          defaultColor: '#23A55A',
                          defaultBorderColor: '#23A55A',
                          defaultHoverColor: '#23A55A',
                          defaultHoverBorderColor: '#23A55A',
                        },
                      },
                    }}
                  >
                    <Button
                      icon={<PlusOutlined />}
                      onClick={handleAddSparepart}
                      size="large"
                    >
                      Add Sparepart
                    </Button>
                  </ConfigProvider>
                </Space>
              </Col>
            </Row>
          </Col>
          <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
            {loading ? (
              <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                minHeight: '200px' 
              }}>
                <Spin size="large" />
              </div>
            ) : (
              <Table
                dataSource={filteredSpareparts}
                columns={columns}
                rowKey="sparepart_id"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
                }}
                scroll={{ x: 1000 }}
                size="middle"
              />
            )}
          </Col>
        </Row>
      </Card>
    </React.Fragment>
  );
});

export default IndexSparepart;