import React, { useEffect, useState } from 'react';
import { useAuth } from '../../context/AuthContext';
import api from '../../utils/api';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Input } from '../../components/ui/input';
import { Label } from '../../components/ui/label';
import { Textarea } from '../../components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '../../components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../components/ui/select';
import { toast } from 'sonner';
import {
  FileText,
  Plus,
  Edit,
  Trash2,
  Calendar,
  ExternalLink
} from 'lucide-react';

const AdminNewsletters = () => {
  const { hasPermission } = useAuth();
  const [newsletters, setNewsletters] = useState([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedNewsletter, setSelectedNewsletter] = useState(null);
  const [newsletterToDelete, setNewsletterToDelete] = useState(null);
  const [uploadedFile, setUploadedFile] = useState(null);
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    published_date: '',
    document_url: '',
    document_type: 'link'
  });
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    fetchNewsletters();
  }, []);

  const fetchNewsletters = async () => {
    try {
      const response = await api.get('/newsletters');
      setNewsletters(response.data);
    } catch (error) {
      toast.error('Failed to fetch newsletters');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setSelectedNewsletter(null);
    setFormData({
      title: '',
      description: '',
      published_date: new Date().toISOString().split('T')[0],
      document_url: '',
      document_type: 'link'
    });
    setUploadedFile(null);
    setDialogOpen(true);
  };

  const handleEdit = (newsletter) => {
    setSelectedNewsletter(newsletter);
    setFormData({
      title: newsletter.title,
      description: newsletter.description || '',
      published_date: new Date(newsletter.published_date).toISOString().split('T')[0],
      document_url: newsletter.document_url,
      document_type: newsletter.document_type
    });
    setDialogOpen(true);
  };

  const handleDelete = (newsletter) => {
    setNewsletterToDelete(newsletter);
    setDeleteDialogOpen(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const formDataToSend = new FormData();
      formDataToSend.append('title', formData.title);
      formDataToSend.append('description', formData.description);
      formDataToSend.append('published_date', new Date(formData.published_date).toISOString());
      formDataToSend.append('document_type', formData.document_type);

      // Handle file upload or URL based on document_type
      if (formData.document_type === 'upload') {
        if (!uploadedFile && !selectedNewsletter) {
          toast.error('Please select a file to upload');
          setSubmitting(false);
          return;
        }
        if (uploadedFile) {
          formDataToSend.append('file', uploadedFile);
        }
      } else {
        formDataToSend.append('document_url', formData.document_url);
      }

      if (selectedNewsletter) {
        await api.put(`/admin/newsletters/${selectedNewsletter.id}`, formDataToSend);
        toast.success('Newsletter updated successfully');
      } else {
        await api.post('/admin/newsletters', formDataToSend);
        toast.success('Newsletter created successfully');
      }

      setDialogOpen(false);
      setUploadedFile(null);
      fetchNewsletters();
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to save newsletter');
    } finally {
      setSubmitting(false);
    }
  };

  const confirmDelete = async () => {
    try {
      await api.delete(`/admin/newsletters/${newsletterToDelete.id}`);
      toast.success('Newsletter deleted successfully');
      setDeleteDialogOpen(false);
      fetchNewsletters();
    } catch (error) {
      toast.error('Failed to delete newsletter');
    }
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const groupByYear = (newsletters) => {
    const grouped = {};
    newsletters.forEach(newsletter => {
      const year = new Date(newsletter.published_date).getFullYear();
      if (!grouped[year]) {
        grouped[year] = [];
      }
      grouped[year].push(newsletter);
    });
    return grouped;
  };

  const groupedNewsletters = groupByYear(newsletters);
  const sortedYears = Object.keys(groupedNewsletters).sort((a, b) => b - a);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <p className="text-brand-purple ">Loading newsletters...</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
            Newsletter Management
          </h1>
          <p className="text-brand-purple  mt-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Create and manage newsletter archive
          </p>
        </div>
        {hasPermission('newsletters.create') && (
          <Button
            onClick={handleCreate}
            className="btn-light-lavender flex items-center gap-2"
          >
            <Plus className="h-4 w-4" />
            Add Newsletter
          </Button>
        )}
      </div>

      {/* Newsletters List */}
      {newsletters.length === 0 ? (
        <Card className="p-12 text-center">
          <FileText className="h-16 w-16 text-[var(--neutral-800)] mx-auto mb-4" />
          <p className="text-brand-purple  text-lg mb-4">No newsletters yet</p>
          {hasPermission('newsletters.create') && (
            <Button onClick={handleCreate} className="bg-brand-purple  text-white">
              <Plus className="h-4 w-4 mr-2" />
              Create First Newsletter
            </Button>
          )}
        </Card>
      ) : (
        <div className="space-y-6">
          {sortedYears.map(year => (
            <div key={year}>
              <h2 className="text-xl font-semibold text-[var(--purple-ink)] mb-4 flex items-center gap-2">
                <Calendar className="h-5 w-5" />
                {year}
              </h2>
              <div className="grid gap-3">
                {groupedNewsletters[year].map(newsletter => (
                  <Card key={newsletter.id} className="p-6">
                    <div className="flex items-start justify-between ">
                      <div className="bg-light-lavender p-3 mr-4 rounded-xl self-center">
                        <FileText className="size-8 " />
                      </div>
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-[var(--purple-ink)] mb-2">
                          {newsletter.title}
                        </h3>
                        {newsletter.description && (
                          <p className="text-brand-purple  mb-3">{newsletter.description}</p>
                        )}
                        <div className="flex items-center gap-3">
                          <Badge className="bg-[var(--neutral-800)] text-[var(--purple-ink)]">
                            {formatDate(newsletter.published_date)}
                          </Badge>
                          <Badge variant="outline" className="border-brand-purple  text-brand-purple ">
                            {newsletter.document_type === 'upload' ? 'PDF Upload' : 'Link'}
                          </Badge>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => window.open(newsletter.document_url, '_blank')}
                            className="text-brand-purple  hover:text-[var(--purple-muted)]"
                          >
                            <ExternalLink className="h-4 w-4 mr-1" />
                            View
                          </Button>
                        </div>
                      </div>
                      {(hasPermission('newsletters.edit') || hasPermission('newsletters.delete')) && (
                        <div className="flex gap-2">
                          {hasPermission('newsletters.edit') && (
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleEdit(newsletter)}
                              className="border-brand-purple  text-brand-purple "
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                          )}
                          {hasPermission('newsletters.delete') && (
                            <Button
                              variant="outline-destructive"
                              size="sm"
                              onClick={() => handleDelete(newsletter)}
                              className=""
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          )}
                        </div>
                      )}
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl overflow-y-auto max-h-[90vh]">
          <DialogHeader>
            <DialogTitle>
              {selectedNewsletter ? 'Edit Newsletter' : 'Add Newsletter'}
            </DialogTitle>
            <DialogDescription>
              {selectedNewsletter ? 'Update newsletter information' : 'Add a new newsletter to the archive'}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit}>
            <div className="space-y-4 py-4">
              <div>
                <Label htmlFor="title">Title *</Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  placeholder="January 2025 Newsletter"
                  required
                />
              </div>

              <div>
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="Monthly community updates and announcements"
                  rows={3}
                />
              </div>

              <div>
                <Label htmlFor="published_date">Published Date *</Label>
                <Input
                  id="published_date"
                  type="date"
                  value={formData.published_date}
                  onChange={(e) => setFormData({ ...formData, published_date: e.target.value })}
                  required
                />
              </div>

              <div>
                <Label htmlFor="document_type">Document Type *</Label>
                <Select
                  value={formData.document_type}
                  onValueChange={(value) => {
                    setFormData({ ...formData, document_type: value, document_url: '' });
                    setUploadedFile(null);
                  }}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="link">Link</SelectItem>
                    <SelectItem value="upload">Upload</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {formData.document_type === 'upload' ? (
                <div>
                  <Label htmlFor="document_file">Upload PDF File *</Label>
                  <Input
                    id="document_file"
                    type="file"
                    accept=".pdf"
                    onChange={(e) => setUploadedFile(e.target.files[0])}
                    required={!selectedNewsletter}
                  />
                  {uploadedFile && (
                    <p className="text-sm text-brand-purple  mt-1">
                      Selected: {uploadedFile.name}
                    </p>
                  )}
                  {selectedNewsletter && !uploadedFile && (
                    <p className="text-sm text-brand-purple  mt-1">
                      Current file will be kept if no new file is selected
                    </p>
                  )}
                </div>
              ) : (
                <div>
                  <Label htmlFor="document_url">Document URL *</Label>
                  <Input
                    id="document_url"
                    value={formData.document_url}
                    onChange={(e) => setFormData({ ...formData, document_url: e.target.value })}
                    placeholder="https://docs.google.com/document/d/... or https://example.com/file.pdf"
                    required
                  />
                  <p className="text-sm text-brand-purple  mt-1">
                    Paste the shareable link to your document (Google Docs, Dropbox, PDF URL, etc.)
                  </p>
                </div>
              )}
            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setDialogOpen(false)}
                disabled={submitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                className="bg-brand-purple  text-white"
                disabled={submitting}
              >
                {submitting ? 'Saving...' : selectedNewsletter ? 'Update' : 'Create'}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Newsletter</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete "{newsletterToDelete?.title}"? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={confirmDelete}
              className="bg-red-500 hover:bg-red-600"
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default AdminNewsletters;
