import React, { useEffect, useState } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  InputAdornment,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  FormControlLabel,
  Switch,
} from "@mui/material";
import { DirectionsCar } from "@mui/icons-material";

export interface Model {
  id: number;
  model_name: string;
}

export interface Vehicle {
  created_at: string;
  id: number;
  plateNo: string | null;
  // status: boolean;
  // updated_at: string;
  vehicleModel: Model;
  vin: string | null;
}

interface EditVehicleDialogProps {
  open: boolean;
  onClose: () => void;
  vehicle: Vehicle | null;
  onVehicleUpdated: () => void;
}

interface VehicleModel {
  id: number;
  model_name: string;
}

export const EditVehicleDialog: React.FC<EditVehicleDialogProps> = ({
  open,
  onClose,
  vehicle,
  onVehicleUpdated,
}) => {
  const [plateNo, setPlateNo] = useState("");
  const [vin, setVin] = useState("");
  const [status, setStatus] = useState(false);
  const [vehicleModelId, setVehicleModelId] = useState<number>(0);
  const [vehicleModels, setVehicleModels] = useState<VehicleModel[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (vehicle) {
      setPlateNo(vehicle.plateNo || "");
      setVin(vehicle.vin || "");
      // setStatus(vehicle.status);
      setVehicleModelId(vehicle.vehicleModel.id);
    }
  }, [vehicle]);

  useEffect(() => {
    const fetchVehicleModels = async () => {
      const token = localStorage.getItem("token");
      if (!token) return;

      setIsLoading(true);
      try {
        const response = await fetch(
          `${process.env.REACT_APP_API_BASE_URL}/vehicleModels`,
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              "x-api-key": token,
            },
          }
        );
        const data = await response.json();
        if (Array.isArray(data)) {
          setVehicleModels(data);
        }
      } catch (error) {
        console.error("Error fetching vehicle models:", error);
      } finally {
        setIsLoading(false);
      }
    };

    if (open) {
      fetchVehicleModels();
    }
  }, [open]);

  const handleSubmit = async () => {
    if (!vehicle) return;

    const token = localStorage.getItem("token");
    if (!token) return;

    const updatedVehicle = {
      plate_no: plateNo,
      vin: vin,
      status: status,
      vehicle_model_id: vehicleModelId,
    };

    setIsLoading(true);
    try {
      const response = await fetch(
        `${process.env.REACT_APP_API_BASE_URL}/vehicle/${vehicle.id}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            "x-api-key": token,
          },
          body: JSON.stringify(updatedVehicle),
        }
      );
      const data = await response.json();
      if (data.message) {
        console.error("Error updating vehicle:", data.message);
      } else {
        onVehicleUpdated();
        onClose();
      }
    } catch (error) {
      console.error("Error updating vehicle:", error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      PaperProps={{
        sx: {
          backgroundColor: "#121212",
          border: "2px solid green",
          borderRadius: "12px",
          padding: "16px",
          width: "400px",
        },
      }}
    >
      <DialogTitle sx={{ color: "green", textAlign: "center" }}>
        Edit Vehicle
      </DialogTitle>
      <DialogContent>
        {/* Plate Number Field */}
        <TextField
          margin="dense"
          label="Plate Number"
          type="text"
          fullWidth
          variant="outlined"
          value={plateNo}
          onChange={(e) => setPlateNo(e.target.value)}
          sx={{
            input: { color: "white" },
            label: { color: "white" },
            "& .MuiOutlinedInput-root": {
              "& fieldset": { borderColor: "white" },
              "&:hover fieldset": { borderColor: "limegreen" },
              "&.Mui-focused fieldset": { borderColor: "limegreen" },
            },
            marginBottom: "16px",
          }}
        />

        {/* VIN Field */}
        <TextField
          margin="dense"
          label="VIN"
          type="text"
          fullWidth
          variant="outlined"
          value={vin}
          onChange={(e) => setVin(e.target.value)}
          sx={{
            input: { color: "white" },
            label: { color: "white" },
            "& .MuiOutlinedInput-root": {
              "& fieldset": { borderColor: "white" },
              "&:hover fieldset": { borderColor: "limegreen" },
              "&.Mui-focused fieldset": { borderColor: "limegreen" },
            },
            marginBottom: "16px",
          }}
        />

        {/* Vehicle Model Dropdown */}
        <FormControl fullWidth sx={{ marginBottom: "16px" }}>
          <InputLabel sx={{ color: "white" }}>Vehicle Model</InputLabel>
          <Select
            value={vehicleModelId}
            onChange={(e) => setVehicleModelId(Number(e.target.value))}
            disabled={isLoading}
            sx={{
              color: "white",
              "& .MuiOutlinedInput-notchedOutline": {
                borderColor: "white",
              },
              "&:hover .MuiOutlinedInput-notchedOutline": {
                borderColor: "limegreen",
              },
              "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                borderColor: "limegreen",
              },
            }}
            inputProps={{
              MenuProps: {
                PaperProps: {
                  sx: {
                    backgroundColor: "#121212",
                    color: "white",
                  },
                },
              },
            }}
            startAdornment={
              <InputAdornment position="start">
                <DirectionsCar sx={{ color: "white", marginRight: 1 }} />
              </InputAdornment>
            }
          >
            {vehicleModels.map((model) => (
              <MenuItem key={model.id} value={model.id}>
                {model.model_name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </DialogContent>
      <DialogActions sx={{ justifyContent: "center" }}>
        <Button
          onClick={onClose}
          disabled={isLoading}
          sx={{
            color: "white",
            border: "1px solid green",
            "&:disabled": {
              opacity: 0.7,
            },
          }}
        >
          Cancel
        </Button>
        <Button
          onClick={handleSubmit}
          disabled={isLoading}
          sx={{
            backgroundColor: "green",
            color: "black",
            "&:disabled": {
              backgroundColor: "darkgreen",
              color: "gray",
            },
          }}
        >
          {isLoading ? "Updating..." : "Update Vehicle"}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default EditVehicleDialog;
