import * as React from 'react';
import { Box, Typography, Divider, IconButton, TextField, Button } from '@mui/material';
import { styled } from '@mui/material/styles';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import { ArticleEditorProps } from '../../types/props';
import { ArticleModel } from "../../types/models";
import { useUpload } from "../../providers/Upload";
import { useArticles } from "../../providers/Article";
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import ImageUploadField from "../ImageUploadField";

const ArticleContainer = styled(Box)(({ theme }) => ({
  maxWidth: '800px',
  margin: '0 auto',
  padding: theme.spacing(4),
  [theme.breakpoints.down('sm')]: {
    padding: theme.spacing(2),
  },
}));

const CoverImage = styled('img')({
  width: '100%',
  height: 'auto',
  borderRadius: '12px',
  marginTop: '16px',
  marginBottom: '24px',
});

export default function ArticleView({
  article,
  onBack,
}: ArticleEditorProps) {

  const { uploadFile } = useUpload();
  const { updateArticle, createArticle } = useArticles();

  const [title, setTitle] = React.useState(article?.title ?? "");
  const [description, setDescription] = React.useState(article?.description ?? "");
  const [tag, setTag] = React.useState(article?.tag ?? "");
  const [img, setImg] = React.useState(article?.img ?? "");
  const [uploadingCoverImage, setUploadingCoverImage] = React.useState(false);
  const [content, setContent] = React.useState(article?.content ?? "");

  const handleCoverImageUpload = async (file: File) => {
    setUploadingCoverImage(true);

    try {
      const img = await uploadFile(file);
      if (img) {
        setImg(img);
      }
    } catch (err) {
      console.error("Avatar upload failed:", err);
    } finally {
      setUploadingCoverImage(false);
    }
  };

  const handleSaveArticle = async (articleData: Partial<ArticleModel>) => {
    // If _id exists → UPDATE
    if (articleData._id) {
      console.log("Updating article with ID:", articleData._id);
      return await updateArticle(articleData as ArticleModel);
    }

    // No _id → CREATE
    console.log("Creating new article:", articleData);
    return await createArticle(articleData as ArticleModel);
  };

  return (
    <ArticleContainer>
      {/* BACK BUTTON */}
      <IconButton onClick={onBack} sx={{ mb: 2 }}>
        <ArrowBackRoundedIcon />
      </IconButton>

      {/* TAG */}
      <TextField
        label="Tag"
        fullWidth
        value={tag}
        onChange={(e) => setTag(e.target.value)}
        sx={{ mb: 2 }}
      />

      {/* TITLE */}
      <TextField
        label="Title"
        fullWidth
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        sx={{ mb: 3 }}
      />

      {/* DESCRIPTION */}
      <TextField
        label="Description"
        fullWidth
        value={description}
        onChange={(e) => setDescription(e.target.value)}
        sx={{ mb: 3 }}
      />

      <Divider sx={{ mb: 3 }} />

      <ImageUploadField
        label="Cover Image"
        value={img}
        uploading={uploadingCoverImage}
        onUpload={handleCoverImageUpload}
        size={128}
      />

      <Divider sx={{ mb: 3 }} />

      {/* MARKDOWN EDITOR */}
      <Box sx={{
        display: 'flex',
        flexDirection: 'column',
        gap: 2,
        alignItems: 'stretch'
      }}>
        <Typography variant="h6">Content</Typography>

        <Box
          component="textarea"
          value={content}
          onChange={(e) => setContent(e.target.value)}
          style={{
            width: '100%',
            minHeight: '300px',
            padding: '16px',
            borderRadius: '8px',
            border: '1px solid rgba(255,255,255,0.2)',
            background: 'transparent',
            color: 'inherit',
            fontFamily: 'monospace',
            fontSize: '16px',
            lineHeight: 1.6,
            resize: 'vertical',
            boxSizing: 'border-box',
          }}
        />

        {/* LIVE PREVIEW */}
        <Typography variant="h6" sx={{ mt: 4 }}>
          Preview
        </Typography>

        <Box
          sx={{
            p: 2,
            border: '1px solid',
            borderColor: 'divider',
            borderRadius: 2,
            '& h3': { fontWeight: 600, mt: 4 },
            '& p': { color: 'text.primary', lineHeight: 1.8, mt: 2 },
            '& em': { fontStyle: 'italic' },
            '& ul': { pl: 3 },
          }}
        >
          <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
        </Box>
      </Box>

      {/* ACTIONS */}
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2, mt: 4 }}>
        <Button variant="outlined" color="secondary" onClick={onBack}>
          Cancel
        </Button>
        <Button
          variant="contained"
          color="primary"
          onClick={() =>
            handleSaveArticle({
              ...article,
              title,
              tag,
              img,
              description,
              content,
            })
          }
        >
          Save Changes
        </Button>
      </Box>
    </ArticleContainer>
  );
}
