"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 { Edit, Search, ChevronLeft, ChevronRight, Eye, X, ArrowUp, ArrowDown, Plus, Trash2, ArrowUpDown } from "lucide-react";
import { toast } from "sonner";
import Editor from "../../../../../src/app/admin/_components/editor/Editor";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
import { useDebounce } from "../../../../../src/hooks/useDebounce";
import { Interweave } from "interweave";

interface EmailTemplate {
  _id: string;
  name: string;
  slug: string;
  subject: string;
  content: string;
  description?: string;
  fromName: string;
  fromEmail: string;
  ccEmail?: string;
  createdAt: string;
  updatedAt: string;
}

export default function ManageEmailTemplates() {
  const [templates, setTemplates] = useState<EmailTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isViewOpen, setIsViewOpen] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<EmailTemplate | null>(null);
  const [viewingTemplate, setViewingTemplate] = useState<EmailTemplate | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [sortField, setSortField] = useState<"name" | "createdAt">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [validationError, setValidationError] = useState({
    name: null,
    subject: null,
    fromEmail: null,
    ccEmail: null
  })
  const [pagination, setPagination] = useState({
    total: 0, pages: 0, page: 1, limit: 10,
  });

  const [formData, setFormData] = useState({
    name: "",
    slug: "",
    subject: "",
    content: "",
    description: "",
    fromName: "",
    fromEmail: "",
    ccEmail: "",
  });

  const debouncedSearch = useDebounce(search, 500)

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

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

  const makeSlug = (text: string) =>
    text.toString().toLowerCase().trim()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/--+/g, '-');

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const hasError = Object.values(validationError).some((err) => err);
    if(hasError) return

    setIsSubmitting(true);
    try {
      const url = editingTemplate ? `/api/email-templates/${editingTemplate._id}` : '/api/email-templates';
      const method = editingTemplate ? '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(editingTemplate ? 'Template updated' : 'Template created');
        setIsDialogOpen(false);
        setEditingTemplate(null);
        resetForm();
        fetchTemplates();
      } else {
        toast.error(result.error || 'Failed to save template');
      }
    } catch {
      toast.error('Error saving template');
    } finally {
      setIsSubmitting(false);
    }
  };

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

  const handleEdit = (template: EmailTemplate) => {
    setEditingTemplate(template);
    setFormData({
      name: template.name,
      slug: template.slug,
      subject: template.subject,
      content: template.content,
      description: template.description || '',
      fromName: template.fromName,
      fromEmail: template.fromEmail,
      ccEmail: template.ccEmail || '',
    });
    setIsDialogOpen(true);
    checkValidation('name', template.name)
    checkValidation('subject', template.subject)
    checkValidation('fromEmail', template.fromEmail)
    checkValidation('ccEmail', template.ccEmail)
  };

  const handleView = (template: EmailTemplate) => {
    console.log('Template', template)
    setViewingTemplate(template);
    setIsViewOpen(true);
  };

  const resetForm = () => {
    setFormData({
      name: "", slug: "", subject: "", content: "",
      description: "", fromName: "", fromEmail: "", ccEmail: "",
    });
  };

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

    switch (key) {
      case 'name': {
        // No special characters — only letters, numbers and spaces
        const nameRegex = /^[a-zA-Z0-9\s]+$/;
        if (!value?.trim()) {
          error = 'Name is required';
        } else if (!nameRegex.test(value)) {
          error = 'Name cannot contain special characters';
        }
        break;
      }
      case 'subject': {
        // No special characters — only letters, numbers and spaces
        const subjectRegex = /^[a-zA-Z0-9\s]+$/;
        if (!value?.trim()) {
          error = 'Subject is required';
        } else if (!subjectRegex.test(value)) {
          error = 'Subject cannot contain special characters';
        }
        break;
      }
      case 'fromEmail': {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!value?.trim()) {
          error = 'From email is required';
        } else if (!emailRegex.test(value)) {
          error = 'Invalid from email address';
        }
        break;
      }
      case 'ccEmail': {
        // CC email is optional — only validate if value is provided
        if (value?.trim()) {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(value)) {
            error = 'Invalid CC email address';
          }
        }
        break;
      }

      default:
        error = null;
    }

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

    return error;
  };

  const inputClass = "w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-1 focus:ring-ring";

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

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

      {/* Search + 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 templates..."
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            className="pl-10"
          />
        </div>
        <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("name")}
              >
                <div className="flex items-center justify-center gap-2">
                  Name
                  {sortField === "name" ? (
                    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">Subject</TableHead>
              <TableHead className="text-center">Template</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> ) : templates.length === 0 ? (
                <TableRow className="bg-white dark:bg-gray-900">
                  <TableCell colSpan={5} className="text-center py-8">
                    No templates found
                  </TableCell>
                </TableRow>
              ) : (
              templates.map((template, index) => (
                <TableRow key={template._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 font-medium">{template.name}</TableCell>
                  <TableCell className="text-center">{template.subject}</TableCell>
                  <TableCell className="text-center font-mono text-xs text-muted-foreground">
                    {template.slug}
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center gap-2">
                      <Tooltip text="View">
                        <Button size="sm" variant="outline" className="border-box" onClick={() => handleView(template)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button size="sm" variant="outline" onClick={() => handleEdit(template)}>
                          <Edit className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button size="sm" variant="outline" onClick={() => handleDelete(template._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-4xl">
          <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>
                  {editingTemplate ? 'Edit Template' : 'Add New Template'}
                </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">
                  {/* Name + Slug */}
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label>Name <span className='text-red-600 font-bold'>*</span></Label>
                      <input
                        className={inputClass}
                        value={formData.name}
                        onChange={(e) => {
                          const val = e.target.value;
                          setFormData(p => ({ ...p, name: val, slug: makeSlug(val) }));
                          checkValidation('name', e.target.value)
                        }}
                        placeholder="e.g. Order Updated"
                        required
                      />
                      {validationError?.name &&
                      <span className='text-sm text-red-400'>{validationError.name}</span>}
                    </div>
                    <div className="space-y-1.5">
                      <Label>From Name <span className='text-red-600 font-bold'>*</span></Label>
                      <input
                        className={inputClass}
                        value={formData.fromName}
                        onChange={(e) => {
                          const val = e.target.value;
                          setFormData(p => ({ ...p, fromName: val }));
                          checkValidation('fromName', e.target.value)
                        }}
                        placeholder="e.g. Order Updated"
                        required
                      />
                      {validationError?.name &&
                      <span className='text-sm text-red-400'>{validationError.name}</span>}
                    </div>
                    <div className="space-y-1.5">
                      <Label>Slug <span className='text-red-600 font-bold'>*</span></Label>
                      <input
                        className={`${inputClass} bg-muted text-muted-foreground cursor-not-allowed`}
                        value={formData.slug}
                        readOnly
                        placeholder="auto-generated"
                      />
                    </div>
                  </div>

                  {/* Subject */}
                  <div className="space-y-1.5">
                    <Label>Subject <span className='text-red-600 font-bold'>*</span></Label>
                    <input
                      className={inputClass}
                      value={formData.subject}
                      onChange={(e) => {
                        setFormData(p => ({ ...p, subject: e.target.value }))
                        checkValidation('subject', e.target.value)
                      }}
                      placeholder="e.g. Your order has been updated"
                      required
                    />
                    {validationError?.subject &&
                      <span className='text-sm text-red-400'>{validationError.subject}</span>}
                  </div>

                  {/* Content — Rich Editor */}
                  <div className="space-y-1.5">
                    <Label>Content <span className='text-red-600 font-bold'>*</span></Label>
                    <>
                      <style>{`
                        .ck.ck-editor__editable {
                          color: #000000 !important;
                          background-color: #ffffff !important;
                          min-height: 200px;
                        }
                        .dark .ck.ck-editor__editable {
                          color: #ffffff !important;
                          background-color: #3B3B3B !important;
                        }
                        .dark .ck.ck-toolbar {
                          background-color: #3B3B3B !important;
                          border-color: #4b5563 !important;
                        }
                        .dark .ck.ck-toolbar .ck-button {
                          color: #ffffff !important;
                        }
                        .dark .ck.ck-toolbar .ck-button:hover {
                          background-color: #4b5563 !important;
                        }
                        .dark .ck.ck-editor__main > .ck-editor__editable {
                          border-color: #4b5563 !important;
                        }
                      `}</style>
                      <Editor
                        key={editingTemplate?._id}
                        value={formData.content}
                        onChange={(value: any) => setFormData(p => ({ ...p, content: value }))}
                      />
                    </>              
                  </div>

                  {/* Description + From Name */}
                  {/* <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label>Description</Label>
                      <input
                        className={inputClass}
                        value={formData.description}
                        onChange={(e) => setFormData(p => ({ ...p, description: e.target.value }))}
                        placeholder="e.g. [order_id],[order_status]"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label>From Name *</Label>
                      <input
                        className={inputClass}
                        value={formData.fromName}
                        onChange={(e) => setFormData(p => ({ ...p, fromName: e.target.value }))}
                        placeholder="e.g. Dulhe Sahab"
                        required
                      />
                    </div>
                  </div> */}

                  {/* From Email + CC Email */}
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label>From Email <span className='text-red-600 font-bold'>*</span></Label>
                      <input
                        type="email"
                        className={inputClass}
                        value={formData.fromEmail}
                        onChange={(e) => {
                          setFormData(p => ({ ...p, fromEmail: e.target.value }))
                          checkValidation('fromEmail', e.target.value)
                        }}
                        placeholder="noreply@dulhesahab.com"
                        required
                      />
                      {validationError?.fromEmail &&
                      <span className='text-sm text-red-400'>{validationError.fromEmail}</span>}
                    </div>
                    <div className="space-y-1.5">
                      <Label>CC Email</Label>
                      <input
                        type="email"
                        className={inputClass}
                        value={formData.ccEmail}
                        onChange={(e) => {
                          setFormData(p => ({ ...p, ccEmail: e.target.value }))
                          checkValidation('ccEmail', e.target.value)
                        }}
                        placeholder="cc@dulhesahab.com"
                      />
                      {validationError?.ccEmail &&
                      <span className='text-sm text-red-400'>{validationError.ccEmail}</span>}
                    </div>
                  </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); setEditingTemplate(null); resetForm(); }}
                  >
                    Cancel
                  </Button>
                  <Button type="submit" className="text-white" disabled={isSubmitting}>
                    {isSubmitting
                      ? (editingTemplate ? 'Updating...' : 'Creating...')
                      : (editingTemplate ? 'Update' : 'Create')
                    }
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* View Dialog */}
      <Dialog open={isViewOpen} onOpenChange={setIsViewOpen}>
        <DialogContent className="max-w-3xl">
          <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>Template Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewOpen(false);
                  }}
                />
              </DialogHeader>
              {viewingTemplate && (
              <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">Name</Label>
                      <p className="text-sm font-medium mt-0.5">{viewingTemplate.name}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-muted-foreground">Slug</Label>
                      <p className="text-sm font-mono mt-0.5">{viewingTemplate.slug}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-muted-foreground">Subject</Label>
                      <p className="text-sm mt-0.5">{viewingTemplate.subject}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-muted-foreground">Description</Label>
                      <p className="text-sm mt-0.5">{viewingTemplate?.description || '-'}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-muted-foreground">From Name</Label>
                      <p className="text-sm mt-0.5">{viewingTemplate.fromName}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-muted-foreground">From Email</Label>
                      <p className="text-sm mt-0.5">{viewingTemplate.fromEmail}</p>
                    </div>
                    {viewingTemplate.ccEmail && (
                      <div>
                        <Label className="text-xs text-muted-foreground">CC Email</Label>
                        <p className="text-sm mt-0.5">{viewingTemplate.ccEmail}</p>
                      </div>
                    )}
                  </div>

                  <div>
                    <Label className="text-xs text-muted-foreground">Content</Label>
                    <div
                      className="mt-1.5 p-4 rounded-md border bg-muted/30 prose prose-sm max-w-none dark:prose-invert dark:text-white"
                      dangerouslySetInnerHTML={{ 
                        __html: viewingTemplate.content
                          .replace(/&lt;/g, '<')
                          .replace(/&gt;/g, '>')
                          .replace(/&amp;/g, '&')
                          .replace(/&quot;/g, '"')
                      }}                 
                    />
                  </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(viewingTemplate); }}
                  >
                    <Edit className="w-4 h-4" /> Edit
                  </Button>
                  <Button
                    variant="danger"
                    size="sm"
                    onClick={() => {
                      setIsViewOpen(false);
                      handleDelete(viewingTemplate._id);
                    }}
                  >
                    <Trash2 className="w-4 h-4" />
                    Delete
                  </Button>
                </div>
              </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

    </div>
  );
}