import { InfoCircleOutlined, LinkOutlined, SearchOutlined } from "@ant-design/icons";
import { Badge, Button, Collapse, Input, Result, Space, Table, Tag, Typography } from "antd";
import _ from "lodash";
import { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectEsResults } from "../../../redux/application/application.selectors";
import { selectBodyshop } from "../../../redux/user/user.selectors";
import EstimateScrubberButton from "../estimate-scrubber-button/estimate-scrubber-button.molecule";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
  esResults: selectEsResults
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(EstimateScrubberResults);

const { Title, Text, Link } = Typography;

export function EstimateScrubberResults({ bodyshop, jobid, job, esResults }) {
  const [searchText, setSearchText] = useState("");
  const buttonDisabled = job?.g_bett_amt == null;

  // Filter items based on search text
  const itemsWithKeys = esResults?.items
    ? esResults.items.map((item, itemIndex) => ({
        ...item,
        scrubberRowKey: [item.SubCategory, item.L, item.R, item.Anchor, itemIndex].filter(Boolean).join("|")
      }))
    : [];

  const filteredItems = itemsWithKeys.length
    ? itemsWithKeys.filter((item) => {
        if (!searchText.trim()) return true;
        const searchLower = searchText.toLowerCase();
        return (
          (item.L && item.L.toLowerCase().includes(searchLower)) ||
          (item.R && item.R.toLowerCase().includes(searchLower))
        );
      })
    : [];

  // Group filtered items by category
  const groupedItems = filteredItems.length
    ? _.groupBy(
        filteredItems.filter((item) => item.SubCategory !== "In Main Display Group - Table Level"),
        "SubCategory"
      )
    : {};

  // Define category colors and priorities
  const categoryConfig = {
    "Administrative Items": { color: "blue", priority: 1, icon: "📎" },
    "Rates Issues": { color: "blue", priority: 2, icon: "💵" },
    "MPI Guidelines Items": { color: "blue", priority: 3, icon: "📋" },
    "Estimator Recommendations": { color: "blue", priority: 4, icon: "✅" },
    "Estimate Parts Found": { color: "blue", priority: 5, icon: "🔧" },
    "All Parts Found": { color: "blue", priority: 6, icon: "🔧" }
  };

  // Sort categories by priority
  const sortedCategories = Object.keys(groupedItems).sort((a, b) => {
    const priorityA = categoryConfig[a]?.priority || 999;
    const priorityB = categoryConfig[b]?.priority || 999;
    return priorityA - priorityB;
  });

  // Define table columns
  const columns = [
    {
      title: "Item",
      dataIndex: "L",
      key: "item",
      width: "25%",
      render: (text, record) => (
        <Space direction="vertical" size="small">
          <Text strong>{text}</Text>
          {record.LinkText && record.Anchor && (
            <Link href={record.Anchor} target="_blank" rel="noopener noreferrer">
              <LinkOutlined /> Learn more
            </Link>
          )}
        </Space>
      )
    },
    {
      title: "Description",
      dataIndex: "R",
      key: "description",
      width: "75%",
      render: (text) => <Text style={{}}>{text}</Text>
    }
  ];

  const collapseItems = sortedCategories.map((category) => {
    const items = groupedItems[category];
    const config = categoryConfig[category] || { color: "default", icon: "📄" };

    return {
      key: category,
      label: (
        <Space>
          {/* <span style={{ fontSize: "18px" }}>{config.icon}</span> */}
          <Text strong>{category}</Text>
          <Badge
            count={items.length}
            style={{
              backgroundColor: config.color === "blue" ? "#1890ff" : config.color === "orange" ? "#fa8c16" : "#52c41a"
            }}
          />
        </Space>
      ),
      children: (
        <Table
          dataSource={items}
          columns={columns}
          pagination={false}
          size="middle"
          rowKey="scrubberRowKey"
          style={{ marginTop: "12px" }}
          scroll={{}}
        />
      )
    };
  });

  if (!esResults?.items?.length || job?.id !== esResults?.jobid) {
    return (
      <Result
        status={buttonDisabled ? "error" : "info"}
        title={buttonDisabled ? "Unable to scrub." : "Estimate Not Scrubbed"}
        subTitle={
          buttonDisabled
            ? "Additional information is required to scrub this estimate. Please reimport the estimate to enable scrubbing."
            : "Run the estimate scrubber to see results here."
        }
        extra={<EstimateScrubberButton key="es" jobid={job ? job.id : null} job={job ? job : null} />}
      />

      // <div style={{ padding: "24px", textAlign: "center" }}>
      //   <InfoCircleOutlined style={{ fontSize: "48px", color: "#d9d9d9", marginBottom: "16px" }} />
      //   <Title level={4} type="secondary">
      //     Estimate not yet scrubbed.
      //   </Title>
      //   <Text type="secondary">Run the estimate scrubber to see results here.</Text>
      //   <EstimateScrubberButton key="es" jobid={job ? job.id : null} job={job ? job : null} />
      // </div>
    );
  }

  // Show empty search results state
  if (searchText && !filteredItems.length) {
    return (
      <div style={{ padding: "16px" }}>
        <Input
          placeholder="Search..."
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          allowClear
          style={{ maxWidth: 400, marginBottom: "24px" }}
        />
        <div style={{ padding: "24px", textAlign: "center" }}>
          <SearchOutlined style={{ fontSize: "48px", color: "#d9d9d9", marginBottom: "16px" }} />
          <Title level={4} type="secondary">
            No items match your search
          </Title>
          <Text type="secondary">Try different keywords or clear the search to see all items.</Text>
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: "16px" }}>
      {Object.keys(groupedItems).length === 0 ? (
        <Result title="Estimate Scrubber did not find any issues." status="success" />
      ) : (
        <Space direction="vertical" size="large" style={{ width: "100%" }}>
          <Space>
            <Input
              placeholder="Search"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
              style={{ maxWidth: 400 }}
            />
            {searchText && (
              <div style={{ marginTop: "8px" }}>
                <Text type="secondary">
                  Showing {filteredItems.length} of {esResults.items.length} items
                </Text>
              </div>
            )}

            <Button
              style={{ float: "right" }}
              type="primary"
              href={esResults?.pdfUrl}
              target="_blank"
              disabled={!esResults?.pdfUrl}
            >
              View PDF
            </Button>
            <Button
              style={{ float: "right" }}
              type="link"
              href={esResults?.reportIssueUrl}
              target="_blank"
              disabled={!esResults?.reportIssueUrl}
            >
              Report Scrubbing Issue
            </Button>
          </Space>
          <Space wrap size={"small"}>
            {Object.entries(groupedItems).map(([category, items]) => {
              const config = categoryConfig[category] || { color: "default" };
              return (
                <Tag key={category} color={config.color}>
                  {category}: {items.length}
                </Tag>
              );
            })}
          </Space>

          <Collapse defaultActiveKey={sortedCategories} expandIconPosition="end" size="large" items={collapseItems} />
        </Space>
      )}
    </div>
  );
}
