'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  IconButton,
  CircularProgress,
  Alert,
  TextField,
  MenuItem,
} from '@mui/material';
import {
  Add,
  Edit,
  Delete,
  Visibility,
  History,
  CheckCircle,
  Cancel,
} from '@mui/icons-material';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';
import { useRouter } from 'next/navigation';

interface LegalPage {
  id: string;
  slug: string;
  title: string;
  language: string;
  version: number;
  isPublished: boolean;
  lastUpdatedBy: string | null;
  createdAt: string;
  updatedAt: string;
}

export default function LegalPagesPage() {
  const router = useRouter();
  const [pages, setPages] = useState<LegalPage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [languageFilter, setLanguageFilter] = useState<string>('all');
  const [publishedFilter, setPublishedFilter] = useState<string>('all');

  useEffect(() => {
    fetchPages();
  }, [languageFilter, publishedFilter]);

  const fetchPages = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();

      if (languageFilter !== 'all') {
        params.append('language', languageFilter);
      }

      if (publishedFilter !== 'all') {
        params.append('isPublished', publishedFilter);
      }

      const response = await apiClient.get(`/api/v1/admin/legal-pages?${params.toString()}`);
      setPages(response.data);
      setError(null);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to fetch legal pages');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this legal page?')) return;

    try {
      await apiClient.delete(`/api/v1/admin/legal-pages/${id}`);
      fetchPages();
    } catch (err: any) {
      alert(err.response?.data?.message || 'Failed to delete legal page');
    }
  };

  const handleTogglePublish = async (page: LegalPage) => {
    try {
      await apiClient.patch(`/api/v1/admin/legal-pages/${page.id}/publish`, {
        isPublished: !page.isPublished,
      });
      fetchPages();
    } catch (err: any) {
      alert(err.response?.data?.message || 'Failed to update publish status');
    }
  };

  return (
    <AdminLayout>
      <Box sx={{ p: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h4">Legal Pages</Typography>
          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={() => router.push('/legal-pages/new')}
          >
            Create Legal Page
          </Button>
        </Box>

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

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
              <TextField
                select
                label="Language"
                value={languageFilter}
                onChange={(e) => setLanguageFilter(e.target.value)}
                sx={{ minWidth: 150 }}
                size="small"
              >
                <MenuItem value="all">All Languages</MenuItem>
                <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>

              <TextField
                select
                label="Status"
                value={publishedFilter}
                onChange={(e) => setPublishedFilter(e.target.value)}
                sx={{ minWidth: 150 }}
                size="small"
              >
                <MenuItem value="all">All Status</MenuItem>
                <MenuItem value="true">Published</MenuItem>
                <MenuItem value="false">Draft</MenuItem>
              </TextField>
            </Box>

            {loading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
                <CircularProgress />
              </Box>
            ) : (
              <TableContainer component={Paper}>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>Title</TableCell>
                      <TableCell>Slug</TableCell>
                      <TableCell>Language</TableCell>
                      <TableCell>Version</TableCell>
                      <TableCell>Status</TableCell>
                      <TableCell>Updated</TableCell>
                      <TableCell align="right">Actions</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {pages.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} align="center">
                          <Typography color="textSecondary">No legal pages found</Typography>
                        </TableCell>
                      </TableRow>
                    ) : (
                      pages.map((page) => (
                        <TableRow key={page.id}>
                          <TableCell>{page.title}</TableCell>
                          <TableCell>
                            <code>{page.slug}</code>
                          </TableCell>
                          <TableCell>{page.language.toUpperCase()}</TableCell>
                          <TableCell>v{page.version}</TableCell>
                          <TableCell>
                            {page.isPublished ? (
                              <Chip
                                icon={<CheckCircle />}
                                label="Published"
                                color="success"
                                size="small"
                              />
                            ) : (
                              <Chip
                                icon={<Cancel />}
                                label="Draft"
                                color="default"
                                size="small"
                              />
                            )}
                          </TableCell>
                          <TableCell>
                            {new Date(page.updatedAt).toLocaleDateString()}
                          </TableCell>
                          <TableCell align="right">
                            <IconButton
                              size="small"
                              onClick={() => router.push(`/legal-pages/${page.id}/edit`)}
                              title="Edit"
                            >
                              <Edit fontSize="small" />
                            </IconButton>
                            <IconButton
                              size="small"
                              onClick={() => router.push(`/legal-pages/${page.id}/versions`)}
                              title="Version History"
                            >
                              <History fontSize="small" />
                            </IconButton>
                            <IconButton
                              size="small"
                              onClick={() => handleTogglePublish(page)}
                              title={page.isPublished ? 'Unpublish' : 'Publish'}
                            >
                              <Visibility fontSize="small" />
                            </IconButton>
                            <IconButton
                              size="small"
                              onClick={() => handleDelete(page.id)}
                              title="Delete"
                              color="error"
                            >
                              <Delete fontSize="small" />
                            </IconButton>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </CardContent>
        </Card>
      </Box>
    </AdminLayout>
  );
}
