"use client";

import React, { useCallback, useState } from "react";
import { Box, Drawer, IconButton, Tab, Tabs, Tooltip, Typography } from "@mui/material";
import {
  Analytics as AnalyticsIcon,
  ChevronLeft,
  ChevronRight,
  FormatListBulleted,
  Search as SearchIcon,
} from "@mui/icons-material";
import AnalysisParameters, {
  createBurstLocationAnalysisParametersState,
  type BurstLocationAnalysisParametersState,
} from "./AnalysisParameters";
import LocationResults from "./LocationResults";
import SchemeQuery, {
  createBurstLocationSchemeQueryState,
  type BurstLocationSchemeQueryState,
} from "./SchemeQuery";
import { BurstLocationResult, BurstSchemeRecord } from "./types";

const TabPanel = ({
  value,
  index,
  children,
}: {
  value: number;
  index: number;
  children: React.ReactNode;
}) => (
  <div role="tabpanel" hidden={value !== index} className="flex-1 overflow-hidden flex flex-col">
    {value === index ? <Box className="flex-1 overflow-auto p-4 flex flex-col">{children}</Box> : null}
  </div>
);

const BurstLocationPanel: React.FC = () => {
  const [open, setOpen] = useState(true);
  const [tab, setTab] = useState(0);
  const [result, setResult] = useState<BurstLocationResult | null>(null);
  const [schemes, setSchemes] = useState<BurstSchemeRecord[]>([]);
  const [analysisState, setAnalysisState] =
    useState<BurstLocationAnalysisParametersState>(
      createBurstLocationAnalysisParametersState,
    );
  const [queryState, setQueryState] =
    useState<BurstLocationSchemeQueryState>(
      createBurstLocationSchemeQueryState,
    );

  const drawerWidth = 450;
  const panelTitle = "爆管定位";

  const handleResult = useCallback((payload: BurstLocationResult) => {
    setResult(payload);
    setTab(2);
  }, []);

  const handleViewResult = useCallback((payload: BurstLocationResult) => {
    setResult(payload);
    setTab(2);
  }, []);

  return (
    <>
      {!open && (
        <Box
          className="absolute top-4 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
          onClick={() => setOpen(true)}
          sx={{ zIndex: 1300 }}
        >
          <Box className="flex flex-col items-center py-3 px-3 gap-1">
            <AnalyticsIcon className="text-[#257DD4] w-5 h-5" />
            <Typography
              variant="caption"
              className="text-gray-700 font-semibold my-1 text-xs"
              style={{ writingMode: "vertical-rl" }}
            >
              {panelTitle}
            </Typography>
            <ChevronLeft className="text-gray-600 w-4 h-4" />
          </Box>
        </Box>
      )}

      <Drawer
        anchor="right"
        open={open}
        variant="persistent"
        hideBackdrop
        sx={{
          width: 0,
          flexShrink: 0,
          "& .MuiDrawer-paper": {
            width: drawerWidth,
            boxSizing: "border-box",
            position: "absolute",
            top: 16,
            right: 16,
            height: "calc(100vh - 32px)",
            maxHeight: "850px",
            borderRadius: "12px",
            boxShadow:
              "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
            backdropFilter: "blur(8px)",
            opacity: 0.95,
            transition: "transform 0.3s ease-in-out, opacity 0.3s ease-in-out",
            border: "none",
            "&:hover": {
              opacity: 1,
            },
          },
        }}
      >
        <Box className="flex flex-col h-full bg-white rounded-xl overflow-hidden">
          <Box className="flex items-center justify-between px-5 py-4 bg-[#257DD4] text-white">
            <Box className="flex items-center gap-2">
              <AnalyticsIcon className="w-5 h-5" />
              <Typography variant="h6" className="text-lg font-semibold">
                {panelTitle}
              </Typography>
            </Box>
            <Tooltip title="收起">
              <IconButton
                size="small"
                onClick={() => setOpen(false)}
                sx={{ color: "primary.contrastText" }}
              >
                <ChevronRight fontSize="small" />
              </IconButton>
            </Tooltip>
          </Box>

          <Box className="border-b border-gray-200 bg-white">
            <Tabs
              value={tab}
              onChange={(_, value) => setTab(value)}
              variant="fullWidth"
              sx={{
                minHeight: 48,
                "& .MuiTab-root": {
                  minHeight: 48,
                  textTransform: "none",
                  fontSize: "0.875rem",
                  fontWeight: 500,
                  transition: "all 0.2s",
                },
                "& .Mui-selected": {
                  color: "#257DD4",
                },
                "& .MuiTabs-indicator": {
                  backgroundColor: "#257DD4",
                },
              }}
            >
              <Tab icon={<AnalyticsIcon fontSize="small" />} iconPosition="start" label="定位参数" />
              <Tab icon={<SearchIcon fontSize="small" />} iconPosition="start" label="方案查询" />
              <Tab icon={<FormatListBulleted fontSize="small" />} iconPosition="start" label="定位结果" />
            </Tabs>
          </Box>

          <TabPanel value={tab} index={0}>
            <AnalysisParameters
              onResult={handleResult}
              state={analysisState}
              onStateChange={setAnalysisState}
            />
          </TabPanel>
          <TabPanel value={tab} index={1}>
            <SchemeQuery
              onViewResult={handleViewResult}
              schemes={schemes}
              onSchemesChange={setSchemes}
              state={queryState}
              onStateChange={setQueryState}
            />
          </TabPanel>
          <TabPanel value={tab} index={2}>
            <LocationResults result={result} />
          </TabPanel>
        </Box>
      </Drawer>
    </>
  );
};

export default BurstLocationPanel;
