'use client';

import { useState, useEffect, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  MenuItem,
  Alert,
  CircularProgress,
  FormControlLabel,
  Switch,
} from '@mui/material';
import { Save, Cancel, Visibility } from '@mui/icons-material';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

// Dynamic import for SimpleMDE to avoid SSR issues
const SimpleMDE = dynamic(() => import('react-simplemde-editor'), { ssr: false });
import 'easymde/dist/easymde.min.css';

interface LegalPage {
  id: string;
  slug: string;
  title: string;
  content: string;
  language: string;
  version: number;
  isPublished: boolean;
}

export default function EditLegalPagePage() {
  const params = useParams();
  const router = useRouter();
  const pageId = params.id as string;
  const isNewPage = pageId === 'new';

  const [loading, setLoading] = useState(!isNewPage);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [content, setContent] = useState('');
  const [language, setLanguage] = useState('en');
  const [isPublished, setIsPublished] = useState(false);

  useEffect(() => {
    if (!isNewPage) {
      fetchPage();
    }
  }, [pageId]);

  const fetchPage = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get(`/api/v1/admin/legal-pages/${pageId}`);
      const page: LegalPage = response.data;
      setTitle(page.title);
      setSlug(page.slug);
      setContent(page.content);
      setLanguage(page.language);
      setIsPublished(page.isPublished);
      setError(null);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to fetch legal page');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      setError(null);

      if (isNewPage) {
        await apiClient.post('/api/v1/admin/legal-pages', {
          slug,
          title,
          content,
          language,
          isPublished,
        });
        setSuccess('Legal page created successfully!');
        setTimeout(() => router.push('/legal-pages'), 1500);
      } else {
        await apiClient.put(`/api/v1/admin/legal-pages/${pageId}`, {
          title,
          content,
          isPublished,
        });
        setSuccess('Legal page updated successfully!');
        setTimeout(() => setSuccess(null), 3000);
      }
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to save legal page');
    } finally {
      setSaving(false);
    }
  };

  const handleTitleChange = (newTitle: string) => {
    setTitle(newTitle);
    // Auto-generate slug from title for new pages
    if (isNewPage) {
      const generatedSlug = newTitle
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');
      setSlug(generatedSlug);
    }
  };

  const mdeOptions = useMemo(() => {
    return {
      spellChecker: false,
      placeholder: 'Enter markdown content here...',
      status: false,
      toolbar: [
        'bold',
        'italic',
        'heading',
        '|',
        'quote',
        'unordered-list',
        'ordered-list',
        '|',
        'link',
        'image',
        '|',
        'preview',
        'side-by-side',
        'fullscreen',
        '|',
        'guide',
      ],
    };
  }, []);

  if (loading) {
    return (
      <AdminLayout>
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
          <CircularProgress />
        </Box>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <Box sx={{ p: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h4">
            {isNewPage ? 'Create Legal Page' : 'Edit Legal Page'}
          </Typography>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              variant="outlined"
              startIcon={<Cancel />}
              onClick={() => router.push('/legal-pages')}
            >
              Cancel
            </Button>
            <Button
              variant="contained"
              startIcon={<Save />}
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? 'Saving...' : 'Save'}
            </Button>
          </Box>
        </Box>

        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}

        {success && (
          <Alert severity="success" sx={{ mb: 3 }}>
            {success}
          </Alert>
        )}

        <Card sx={{ mb: 3 }}>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>
              Page Information
            </Typography>

            <Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: '1fr 1fr' }}>
              <TextField
                label="Title"
                value={title}
                onChange={(e) => handleTitleChange(e.target.value)}
                fullWidth
                required
              />

              <TextField
                label="Slug"
                value={slug}
                onChange={(e) => setSlug(e.target.value)}
                fullWidth
                required
                disabled={!isNewPage}
                helperText={isNewPage ? 'Auto-generated from title' : 'Cannot change slug after creation'}
              />

              <TextField
                select
                label="Language"
                value={language}
                onChange={(e) => setLanguage(e.target.value)}
                fullWidth
                disabled={!isNewPage}
              >
                <MenuItem value="en">English</MenuItem>
                <MenuItem value="es">Spanish</MenuItem>
                <MenuItem value="fr">French</MenuItem>
                <MenuItem value="pt">Portuguese</MenuItem>
                <MenuItem value="zh">Chinese</MenuItem>
              </TextField>

              <FormControlLabel
                control={
                  <Switch
                    checked={isPublished}
                    onChange={(e) => setIsPublished(e.target.checked)}
                  />
                }
                label="Published"
              />
            </Box>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>
              Content (Markdown)
            </Typography>

            <Box sx={{ mb: 2 }}>
              <SimpleMDE
                value={content}
                onChange={setContent}
                options={mdeOptions}
              />
            </Box>

            <Typography variant="h6" sx={{ mb: 2, mt: 4 }}>
              Preview
            </Typography>

            <Box
              sx={{
                border: '1px solid #ddd',
                borderRadius: 1,
                p: 3,
                backgroundColor: '#f9f9f9',
                '& h1': { fontSize: '2rem', mb: 2 },
                '& h2': { fontSize: '1.5rem', mb: 2, mt: 3 },
                '& h3': { fontSize: '1.25rem', mb: 1, mt: 2 },
                '& p': { mb: 2 },
                '& ul, & ol': { mb: 2, pl: 3 },
                '& li': { mb: 1 },
                '& code': { backgroundColor: '#e0e0e0', p: 0.5, borderRadius: 0.5 },
                '& pre': { backgroundColor: '#e0e0e0', p: 2, borderRadius: 1, overflow: 'auto' },
              }}
            >
              <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
            </Box>
          </CardContent>
        </Card>
      </Box>
    </AdminLayout>
  );
}
