"use client";

import { useEffect, useState } from "react";
import {
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DataGrid, GridColDef, GridRenderCellParams, GridPaginationModel } from "@mui/x-data-grid";
import EditIcon from "@mui/icons-material/Edit";
import SaveIcon from "@mui/icons-material/Save";
import CloseIcon from "@mui/icons-material/Close";
import { Models } from "@/app/components/ModelGrid";

const ModelDataTable: React.FC = () => {
  const [models, setModels] = useState<Models[]>([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(0); // DataGrid uses 0-based page
  const [pageSize, setPageSize] = useState(10);
  const [editModel, setEditModel] = useState<Models | null>(null);
  const [saving, setSaving] = useState(false);
  const [editOpen, setEditOpen] = useState(false);

  const fetchModels = async (pageNum: number, limit: number) => {
    setLoading(true);
    try {
      const res = await fetch(`/api/models?page=${pageNum + 1}&limit=${limit}`);
      const data = await res.json();
      setModels(data.data);
      setTotal(data.total);
    } catch (error) {
      console.error("Failed to fetch models:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchModels(page, pageSize);
  }, [page, pageSize]);

  const handleEditOpen = (model: Models) => {
    setEditModel({ ...model });
    setEditOpen(true);
  };

  const handleEditClose = () => {
    setEditOpen(false);
    setEditModel(null);
  };

  const handleEditChange = (field: keyof Models, value: string) => {
    if (!editModel) return;
    setEditModel((prev) => ({ ...prev!, [field]: value }));
  };

  const handleSave = async () => {
    if (!editModel) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/models/${editModel.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editModel),
      });
      if (!res.ok) throw new Error("Failed to update model");
      // Refresh table
      await fetchModels(page, pageSize);
      handleEditClose();
    } catch (error) {
      console.error("Failed to save model:", error);
    } finally {
      setSaving(false);
    }
  };

  const columns: GridColDef[] = [
    {
      field: "id",
      headerName: "ID",
      width: 70,
    },
    {
      field: "image",
      headerName: "Image",
      width: 80,
      sortable: false,
      renderCell: (params: GridRenderCellParams) => (
        <Box
          component="img"
          src={`/assets/${params.value}`}
          alt={params.row.title}
          sx={{ width: 45, height: 45, objectFit: "cover", borderRadius: 1, my: 0.5 }}
          onError={(e: React.SyntheticEvent<HTMLImageElement>) => {
            e.currentTarget.src = "/placeholder.png";
          }}
        />
      ),
    },
    {
      field: "title",
      headerName: "Title",
      flex: 1,
      minWidth: 150,
    },
    {
      field: "category",
      headerName: "Category",
      width: 130,
      renderCell: (params: GridRenderCellParams) => (
        <Chip label={params.value} size="small" color="primary" variant="outlined" />
      ),
    },
    {
      field: "description",
      headerName: "Description",
      flex: 2,
      minWidth: 200,
      renderCell: (params: GridRenderCellParams) => (
        <Tooltip title={params.value}>
          <Typography
            variant="body2"
            sx={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              maxWidth: 300,
            }}
          >
            {params.value}
          </Typography>
        </Tooltip>
      ),
    },
    {
      field: "hotspots",
      headerName: "Hotspots",
      width: 100,
      sortable: false,
      renderCell: (params: GridRenderCellParams) => (
        <Chip
          label={params.value?.length ?? 0}
          size="small"
          color={params.value?.length > 0 ? "success" : "default"}
        />
      ),
    },
    {
      field: "program",
      headerName: "Program",
      width: 120,
    },
    {
      field: "actions",
      headerName: "Actions",
      width: 100,
      sortable: false,
      renderCell: (params: GridRenderCellParams) => (
        <Tooltip title="Edit Model">
          <IconButton
            color="primary"
            onClick={() => handleEditOpen(params.row as Models)}
            size="small"
          >
            <EditIcon fontSize="small" />
          </IconButton>
        </Tooltip>
      ),
    },
  ];

  return (
    <Box sx={{ width: "100%" }}>
      <Typography variant="h5" fontWeight={700} mb={2}>
        Models Management
      </Typography>

      <DataGrid
        rows={models}
        columns={columns}
        rowCount={total}
        loading={loading}
        paginationMode="server"
        paginationModel={{ page, pageSize }}
        onPaginationModelChange={(model: GridPaginationModel) => {
          setPage(model.page);
          setPageSize(model.pageSize);
        }}
        pageSizeOptions={[5, 10, 25, 50]}
        rowHeight={60}
        disableRowSelectionOnClick
        sx={{
          borderRadius: 2,
          "& .MuiDataGrid-columnHeader": {
            backgroundColor: "#f5f5f5",
            fontWeight: 700,
          },
          "& .MuiDataGrid-row:hover": {
            backgroundColor: "#f0f7ff",
          },
        }}
      />

      {/* Edit Dialog */}
      <Dialog open={editOpen} onClose={handleEditClose} fullWidth maxWidth="sm">
        <DialogTitle
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <Typography fontWeight={700}>Edit Model — {editModel?.title}</Typography>
          <IconButton onClick={handleEditClose} size="small">
            <CloseIcon />
          </IconButton>
        </DialogTitle>

        <DialogContent dividers>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, pt: 1 }}>
            <TextField
              label="Title"
              fullWidth
              value={editModel?.title ?? ""}
              onChange={(e) => handleEditChange("title", e.target.value)}
            />
            <TextField
              label="Description"
              fullWidth
              multiline
              rows={3}
              value={editModel?.description ?? ""}
              onChange={(e) => handleEditChange("description", e.target.value)}
            />
            <TextField
              label="Category"
              fullWidth
              value={editModel?.category ?? ""}
              onChange={(e) => handleEditChange("category", e.target.value)}
            />
            <TextField
              label="Program"
              fullWidth
              value={editModel?.program ?? ""}
              onChange={(e) => handleEditChange("program", e.target.value)}
            />
            <TextField
              label="Speech Text"
              fullWidth
              multiline
              rows={2}
              value={editModel?.speachtext ?? ""}
              onChange={(e) => handleEditChange("speachtext", e.target.value)}
            />
            <TextField
              label="Tag"
              fullWidth
              value={editModel?.tag ?? ""}
              onChange={(e) => handleEditChange("tag", e.target.value)}
            />
          </Box>
        </DialogContent>

        <DialogActions sx={{ px: 3, py: 2 }}>
          <Button onClick={handleEditClose} color="inherit" startIcon={<CloseIcon />}>
            Cancel
          </Button>
          <Button
            onClick={handleSave}
            variant="contained"
            startIcon={saving ? <CircularProgress size={16} color="inherit" /> : <SaveIcon />}
            disabled={saving}
          >
            {saving ? "Saving..." : "Save Changes"}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ModelDataTable;