import React, { useState } from "react";
import { X } from "@mui/icons-material";
import { DefectsSectionProps, QualityCheckItem } from "./types";
import {
  Autocomplete,
  TextField,
  Button,
  Typography,
  Box,
  Stack,
  Paper,
  IconButton,
} from "@mui/material";
import { defectOptions } from "./dummyData";

const DefectsSection: React.FC<DefectsSectionProps> = ({
  defects,
  onDefectsChange,
  error,
}) => {
  const [newDefect, setNewDefect] = useState<QualityCheckItem | null>(null);
  const [inputValue, setInputValue] = useState<string>("");

  const handleAddDefect = (): void => {
    let defectToAdd: QualityCheckItem | null = null;

    if (newDefect) {
      // If user selected from options
      defectToAdd = {
        id: newDefect.id,
        code: newDefect.code,
        name: newDefect.name,
        description: newDefect.description,
      };
    }

    if (defectToAdd) {
      // Check for duplicate code (skip if code is empty)
      const isDuplicate =
        defectToAdd.code && defects.some((d) => d.code === defectToAdd!.code);
      if (!isDuplicate) {
        const updatedDefects = [...defects, defectToAdd];
        onDefectsChange(updatedDefects);
      }
      setNewDefect(null);
      setInputValue("");
    }
  };

  const handleRemoveDefect = (index: number): void => {
    const updatedDefects = defects.filter((_, i) => i !== index);
    onDefectsChange(updatedDefects);
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>): void => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleAddDefect();
    }
  };

  return (
    <Box>
      <Typography variant="subtitle1" fontWeight={600} mb={1}>
        Defects Found
      </Typography>
      <Stack direction="row" spacing={2} mb={2}>
        <Autocomplete
          value={newDefect}
          onChange={(event, value) => {
            if (typeof value === "string") {
              setNewDefect({ id: 0, code: "", name: value, description: "" });
            } else {
              setNewDefect(value);
            }
          }}
          inputValue={inputValue}
          onInputChange={(event, newInputValue: string) => {
            setInputValue(newInputValue);
          }}
          options={defectOptions}
          getOptionLabel={(option) =>
            typeof option === "string"
              ? option
              : `${option.code} - ${option.name}`
          }
          isOptionEqualToValue={(option, value) => option.id === value.id}
          fullWidth
          renderOption={(props, option) => (
            <Box component="li" {...props} key={option.id}>
              <Box>
                <Typography variant="body2" fontWeight={500}>
                  {option.code} - {option.name}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  {option.description}
                </Typography>
              </Box>
            </Box>
          )}
          renderInput={(params) => (
            <TextField
              {...params}
              size="small"
              label="Enter defect description"
              variant="outlined"
              onKeyDown={handleKeyPress}
              error={!!error}
            />
          )}
        />
        <Button variant="contained" color="primary" onClick={handleAddDefect}>
          Add
        </Button>
      </Stack>

      {error && (
        <Typography
          variant="caption"
          color="error"
          sx={{ mb: 1, display: "block" }}
        >
          {error}
        </Typography>
      )}

      {defects.length > 0 && (
        <Stack spacing={1}>
          <Typography variant="body2" color="text.secondary" mb={1}>
            {defects.length} defect(s) found
          </Typography>
          {defects.map((defect: QualityCheckItem, index: number) => (
            <Paper
              key={`${defect.id}-${index}`}
              sx={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                bgcolor: "red.50",
                border: "1px solid",
                borderColor: "red.200",
                p: 1.5,
              }}
              elevation={0}
            >
              <Box>
                <Typography
                  color="error"
                  sx={{ wordBreak: "break-word", fontWeight: 500 }}
                >
                  {defect.code && `${defect.code} - `}
                  {defect.name}
                </Typography>
                {defect.description && (
                  <Typography
                    variant="caption"
                    color="error"
                    sx={{ opacity: 0.7 }}
                  >
                    {defect.description}
                  </Typography>
                )}
              </Box>
              <IconButton
                onClick={() => handleRemoveDefect(index)}
                color="error"
                size="small"
              >
                <X fontSize="small" />
              </IconButton>
            </Paper>
          ))}
        </Stack>
      )}
    </Box>
  );
};

export default DefectsSection;
