"use client";

import { useState, useEffect } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../../../../src/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../src/components/ui/table";
import { Badge } from "../../../../../src/components/ui/badge";
import { Plus, X, Edit, Trash2, Search, ChevronLeft, ChevronRight, Eye, ArrowUp, ArrowDown, ArrowUpDown } from "lucide-react";
import { toast } from "sonner";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
import { useDebounce } from "../../../../../src/hooks/useDebounce";

interface Subscriber {
  _id: string;
  email: string;
  status: 'active' | 'inactive';
  subscribedAt: string;
  createdAt: string;
}

export default function ManageNewsletter() {
  const [subscribers, setSubscribers] = useState<Subscriber[]>([]);
  const [loading, setLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingSubscriber, setEditingSubscriber] = useState<Subscriber | null>(null);
  const [isViewOpen, setIsViewOpen] = useState(false);
  const [viewingSubscriber, setViewingSubscriber] = useState<Subscriber | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [statusFilter, setStatusFilter] = useState("");
  const [sortField, setSortField] = useState<"email" | "createdAt">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
  const [pagination, setPagination] = useState({
    total: 0, pages: 0, page: 1, limit: 10,
  });

  const [formData, setFormData] = useState({
    email:  "",
    status: "active",
  });

  const [validationError, setValidationError] = useState({
      email: null
  })

  const checkValidation = (key: string, value: any) => {
    let error = null;

    switch (key) {
      case 'email': {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!value?.trim()) {
          error = 'Email is required';
        } else if (!emailRegex.test(value)) {
          error = 'Invalid email address';
        }
        break;
      }
      default:
        error = null;
    }

    setValidationError((prev: any) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const debouncedSearch = useDebounce(search, 500)

  useEffect(() => { fetchSubscribers(); }, [debouncedSearch, page, limit, statusFilter, sortField, sortOrder]);

  const fetchSubscribers = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page:  page.toString(),
        limit: limit.toString(),
        sort:  sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch }),
        ...(statusFilter && { status: statusFilter }),
      });
      const res = await fetch(`/api/newsletter?${params}`);
      const result = await res.json();
      if (result.success) {
        setSubscribers(result.data);
        setPagination(result.pagination);
      } else {
        toast.error('Failed to fetch subscribers');
      }
    } catch {
      toast.error('Error fetching subscribers');
    } finally {
      setLoading(false);
    }
  };

  const handleSort = (field: "email" | "createdAt") => {
    if (sortField === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortOrder("asc");
    }
    setPage(1);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const url = editingSubscriber ? `/api/newsletter/${editingSubscriber._id}` : '/api/newsletter';
      const method = editingSubscriber ? 'PUT' : 'POST';

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
      const result = await res.json();

      if (result.success) {
        toast.success(editingSubscriber ? 'Subscriber updated' : 'Subscriber added');
        setIsDialogOpen(false);
        setEditingSubscriber(null);
        resetForm();
        fetchSubscribers();
      } else {
        toast.error(result.error || 'Failed to save');
      }
    } catch {
      toast.error('Error saving subscriber');
    }
  };

  const handleEdit = (subscriber: Subscriber) => {
    setEditingSubscriber(subscriber);
    setFormData({ email: subscriber.email, status: subscriber.status });
    checkValidation('email', subscriber.email)
    setIsDialogOpen(true);
  };

  const handleView = (subscriber: Subscriber) => {
    setViewingSubscriber(subscriber);
    setIsViewOpen(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this subscriber?')) return;
    try {
      const res = await fetch(`/api/newsletter/${id}`, { method: 'DELETE' });
      const result = await res.json();
      if (result.success) {
        toast.success('Subscriber deleted');
        fetchSubscribers();
      } else {
        toast.error(result.error || 'Failed to delete');
      }
    } catch {
      toast.error('Error deleting subscriber');
    }
  };

  const resetForm = () => {
    setFormData({ email: "", status: "active" });
    setValidationError({ email: null })
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString("en-IN", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return (
    <div className="space-y-6">

      {/* Header */}
      {/* <div className="flex justify-between items-center"> */}
        {/* <h2 className="text-2xl font-bold">Manage Newsletter</h2> */}
        {/* <div className="text-sm text-gray-500 bg-gray-100 dark:bg-gray-800 px-3 py-1 rounded">
          Total Subscribers: {pagination.total}
        </div> */}
        {/* <Button
          onClick={() => { resetForm(); setEditingSubscriber(null); setIsDialogOpen(true); }}
          className="text-white"
        >
          <Plus className="w-4 h-4" />
          Add Subscriber
        </Button> */}
      {/* </div> */}

      {/* Search + Filter + Limit */}
      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            placeholder="Search by email..."
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            className="pl-10"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
          className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"
        >
          <option value="">All Status</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
        <div className="flex items-center gap-2">
          <Label className="text-sm whitespace-nowrap">Show:</Label>
          <select
            value={limit.toString()}
            onChange={(e) => { setLimit(parseInt(e.target.value)); setPage(1); }}
            className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"
          >
            <option value="6">6</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </div>
      </div>

      {/* Table */}
      <div className="rounded-md border">
        <Table>
          <TableHeader className="bg-gray-100 dark:bg-gray-800">
            <TableRow className="bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800">
              <TableHead
                className="text-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700"
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-2">
                  ID
                  {sortField === "createdAt" ? (
                    sortOrder === "asc"
                      ? <ArrowUp className="h-4 w-4" />
                      : <ArrowDown className="h-4 w-4" />
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              <TableHead
                className="text-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700"
                onClick={() => handleSort("email")}
              >
                <div className="flex items-center justify-center gap-2">
                  Email
                  {sortField === "email" ? (
                    sortOrder === "asc"
                      ? <ArrowUp className="h-4 w-4" />
                      : <ArrowDown className="h-4 w-4" />
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              {/* <TableHead className="text-center">Status</TableHead> */}
              <TableHead className="text-center">Subscribed At</TableHead>
              <TableHead className="text-center">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className="dark:bg-[#1f2a37]">
            {loading ? (
              <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                <TableCell colSpan={6} className="px-4 py-8 text-center">
                  <div className="flex items-center justify-center">
                    <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                      <span className="ml-2">Loading...</span>
                    </div>
                </TableCell>
              </TableRow>) : subscribers.length === 0 ? (
                <TableRow className="bg-white dark:bg-gray-900">
                  <TableCell colSpan={5} className="text-center py-8">
                    No subscribers found
                  </TableCell>
                </TableRow>
              ) : (
              subscribers.map((subscriber, index) => (
                <TableRow key={subscriber._id} className="bg-white dark:bg-gray-900">
                  <TableCell className="text-center">
                    {sortField === "createdAt" && sortOrder === "desc"
                      ? pagination.total - ((pagination.page - 1) * pagination.limit) - index  // desc
                      : ((pagination.page - 1) * pagination.limit) + index + 1                 // asc
                    }
                  </TableCell>
                  <TableCell className="text-center">{subscriber.email}</TableCell>
                  {/* <TableCell className="text-center">
                    <Badge variant={subscriber.status === 'active' ? 'default' : 'secondary'}>
                      {subscriber.status === 'active' ? 'Active' : 'Inactive'}
                    </Badge>
                  </TableCell> */}
                  <TableCell className="text-center text-sm text-muted-foreground">
                    {formatDate(subscriber.subscribedAt || subscriber.createdAt)}
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center gap-2">
                      <Tooltip text="View">
                        <Button size="sm" variant="outline" onClick={() => handleView(subscriber)}>
                            <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      {/* <Tooltip text="Edit">
                        <Button size="sm" variant="outline" onClick={() => handleEdit(subscriber)}>
                            <Edit className="w-4 h-4" />
                        </Button>
                      </Tooltip> */}
                      <Tooltip text="Delete">
                        <Button size="sm" variant="outline" onClick={() => handleDelete(subscriber._id)}>
                            <Trash2 className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} results
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => setPage(page - 1)} disabled={page === 1}>
              <ChevronLeft className="h-4 w-4" /> Previous
            </Button>
            <span className="text-sm">Page {page} of {pagination.pages}</span>
            <Button variant="outline" size="sm" onClick={() => setPage(page + 1)} disabled={page === pagination.pages}>
              Next <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Add/Edit Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-md">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>
                  {editingSubscriber ? 'Edit Subscriber' : 'Add Subscriber'}
                  
                </DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                    onClick={() => {
                      setIsDialogOpen(false);
                    }}
                  />
              </DialogHeader>
       
              <form onSubmit={handleSubmit} className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                  <div className="mb-4 space-y-1.5">
                    <Label htmlFor="email">Email <span className='text-red-600 font-bold'>*</span></Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => {
                        setFormData(p => ({ ...p, email: e.target.value }))
                        checkValidation('email', e.target.value)
                      }}
                      placeholder="subscriber@example.com"
                      required
                    />
                    {validationError?.email &&
                      <span className='text-sm text-red-400'>{validationError.email}</span>}
                  </div>
                  {editingSubscriber && <div>
                    <Label htmlFor="status">Status</Label>
                    <select
                      id="status"
                      value={formData.status}
                      onChange={(e) => setFormData(p => ({ ...p, status: e.target.value }))}
                      className="w-full mt-1 px-3 py-2 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"
                    >
                      <option value="active">Active</option>
                      <option value="inactive">Inactive</option>
                    </select>
                  </div>}
                </div>
                <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => { setIsDialogOpen(false); setEditingSubscriber(null); resetForm(); }}
                  >
                    Cancel
                  </Button>
                  <Button type="submit" className="text-white">
                    {editingSubscriber ? 'Update' : 'Add'}
                  </Button>
                </div>
              </form>
             
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* View Dialog */}
      <Dialog open={isViewOpen} onOpenChange={setIsViewOpen}>
        <DialogContent className="max-w-md">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Subscriber Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewOpen(false);
                  }}
                />
              </DialogHeader>
              {viewingSubscriber && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label className="text-xs text-muted-foreground">Email</Label>
                        <p className="text-sm font-medium mt-0.5">{viewingSubscriber.email}</p>
                      </div>
                      <div>
                        <Label className="text-xs text-muted-foreground">Status</Label>
                        <div className="mt-1">
                          <Badge variant={viewingSubscriber.status === 'active' ? 'default' : 'secondary'}>
                            {viewingSubscriber.status === 'active' ? 'Active' : 'Inactive'}
                          </Badge>
                        </div>
                      </div>
                      <div>
                        <Label className="text-xs text-muted-foreground">Subscribed At</Label>
                        <p className="text-xs mt-0.5">{formatDate(viewingSubscriber.subscribedAt || viewingSubscriber.createdAt)}</p>
                      </div>
                      <div>
                        <Label className="text-xs text-muted-foreground">Last Updated</Label>
                        <p className="text-xs mt-0.5">{formatDate(viewingSubscriber.createdAt)}</p>
                      </div>
                    </div>
                  </div>
                  <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => { setIsViewOpen(false); handleEdit(viewingSubscriber); }}
                    >
                      <Edit className="w-4 h-4" /> Edit
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => { setIsViewOpen(false); handleDelete(viewingSubscriber._id); }}
                    >
                      <Trash2 className="w-4 h-4" /> Delete
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

    </div>
  );
}