"use client";

import { useEffect, useState, type FormEvent } from "react";
import { apiCall } from "@/utils/callApi";
import { toast } from "sonner";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Textarea } from "../../../../../src/components/ui/textarea";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../src/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../../../../../src/components/ui/dialog";
import {
  Eye,
  Search,
  Plus,
  Edit,
  Trash2,
  X,
  Check,
  ArrowLeft,
  ArrowRight,
  ChevronRight,
  ChevronLeft,
} from "lucide-react";
import ExportExcel from "@/components/ui-elements/ExportExcel";
import * as XLSX from "xlsx";

interface ContactItem {
  _id: string;
  name: string;
  email: string;
  phone: string;
  message: string;
  isRead: boolean;
  createdAt: string;
  updatedAt: string;
}

const defaultForm = {
  name: "",
  email: "",
  phone: "",
  message: "",
};

const ContactManagement = () => {
  const [contacts, setContacts] = useState<ContactItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0,
  });
  const [isViewOpen, setIsViewOpen] = useState(false);
  const [viewingContact, setViewingContact] = useState<ContactItem | null>(
    null,
  );
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [form, setForm] = useState(defaultForm);
  const [selectedContactId, setSelectedContactId] = useState<string | null>(
    null,
  );
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    fetchContacts();
  }, [search, page, limit]);

  const fetchContacts = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      params.set("page", String(page));
      params.set("limit", String(limit));
      if (search.trim()) {
        params.set("search", search.trim());
      }

      const response = await apiCall<{
        success: boolean;
        data: ContactItem[];
        pagination: any;
      }>(`/api/contact?${params.toString()}`);

      if (!response.data || !response.data.success) {
        toast.error(response.error || "Failed to load contacts.");
        return;
      }

      setContacts(response.data.data || []);
      setPagination(
        response.data.pagination || { page, limit, total: 0, pages: 0 },
      );
    } catch (error) {
      console.error(error);
      toast.error("Error loading contacts.");
    } finally {
      setLoading(false);
    }
  };

  const downloadExcel = async () => {
    try {
      const params = new URLSearchParams({
        page: "1",
        limit: "1000",
        ...(search && { search: search }),
        sort: "createdAt",
        order: "desc",
      });

      const response: any = await apiCall<{
        success: boolean;
        data: ContactItem[];
        pagination: any;
      }>(`/api/contact?${params.toString()}`);

      if (response?.data.success) {
        const modData = response?.data?.data?.map((dt: any) => ({
          name: dt.name,
          phone: dt?.phone || "",
          email: dt?.email || "",
          message: dt?.message || "",
          createdAt: dt?.createdAt
            ? new Date(dt.createdAt).toLocaleDateString()
            : "",
        }));
        // Convert JSON to worksheet
        const worksheet = XLSX.utils.json_to_sheet(modData);

        // Create workbook
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Contacts");

        // Download file
        XLSX.writeFile(workbook, "contacts.xlsx");
        toast.success("Excel downloaded successfully");
      }
    } catch (error) {
      console.error("Error fetching data", error);
    }
  };

  const resetForm = () => {
    setForm(defaultForm);
    setSelectedContactId(null);
    setIsEditMode(false);
  };

  const openCreateDialog = () => {
    resetForm();
    setIsDialogOpen(true);
  };

  const openEditDialog = (contact: ContactItem) => {
    setIsEditMode(true);
    setSelectedContactId(contact._id);
    setForm({
      name: contact.name,
      email: contact.email,
      phone: contact.phone,
      message: contact.message,
    });
    setIsDialogOpen(true);
  };

  const openViewDialog = (contact: ContactItem) => {
    setViewingContact(contact);
    setIsViewOpen(true);
  };

  const closeDialog = () => {
    setIsDialogOpen(false);
    resetForm();
  };

  const handleSave = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (
      !form.name.trim() ||
      !form.email.trim() ||
      !form.phone.trim() ||
      !form.message.trim()
    ) {
      toast.error("All fields are required.");
      return;
    }

    try {
      setIsSubmitting(true);
      const payload = {
        name: form.name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        message: form.message.trim(),
      };

      const response = await apiCall<{ success: boolean; data: ContactItem }>(
        isEditMode && selectedContactId
          ? `/api/contact?id=${selectedContactId}`
          : "/api/contact",
        {
          method: isEditMode ? "PUT" : "POST",
          body: payload,
        },
      );

      if (!response.data || !response.data.success) {
        toast.error(response.error || "Unable to save contact.");
        return;
      }

      toast.success(isEditMode ? "Contact updated." : "Contact created.");
      closeDialog();
      setPage(1);
      void fetchContacts();
    } catch (error) {
      console.error(error);
      toast.error("Error saving contact.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm("Delete this contact?")) {
      return;
    }

    try {
      const response = await apiCall<{ success: boolean; message: string }>(
        `/api/contact?id=${id}`,
        { method: "DELETE" },
      );

      if (!response.data || !response.data.success) {
        toast.error(response.error || "Unable to delete contact.");
        return;
      }

      toast.success("Contact deleted.");
      if (contacts.length === 1 && page > 1) {
        setPage(page - 1);
      } else {
        void fetchContacts();
      }
    } catch (error) {
      console.error(error);
      toast.error("Error deleting contact.");
    }
  };

  const handleToggleRead = async (contact: ContactItem) => {
    try {
      const response = await apiCall<{ success: boolean; data: ContactItem }>(
        `/api/contact?id=${contact._id}`,
        {
          method: "PATCH",
          body: { isRead: !contact.isRead },
        },
      );

      if (!response.data || !response.data.success) {
        toast.error(response.error || "Unable to update status.");
        return;
      }

      toast.success(
        `Contact marked as ${!contact.isRead ? "read" : "unread"}.`,
      );
      void fetchContacts();
    } catch (error) {
      console.error(error);
      toast.error("Error updating contact status.");
    }
  };

  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > pagination.pages) return;
    setPage(newPage);
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-center">
          <div className="relative w-full max-w-sm">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <Input
              className="pl-10"
              placeholder="Search contacts..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
            />
          </div>

          <select
            value={limit}
            onChange={(e) => {
              setLimit(Number(e.target.value));
              setPage(1);
            }}
            className="rounded-md border px-3 py-2"
          >
            <option value={5}>5</option>
            <option value={10}>10</option>
            <option value={20}>20</option>
            <option value={50}>50</option>
          </select>
        </div>

        <div className="flex items-center gap-2">
          {/* <Button size="sm" onClick={openCreateDialog}>
            <Plus className="mr-2 h-4 w-4" />
            New Contact
          </Button> */}
          <ExportExcel downloadExcel={downloadExcel} />
        </div>
      </div>

      <div className="overflow-x-auto rounded-lg border bg-white p-0 shadow-sm">
        <Table>
          <TableHeader className="dark:bg-gray-800">
            <TableRow>
              <TableHead className="w-[50px] text-center">#</TableHead>
              <TableHead>Name</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Phone</TableHead>
              {/* <TableHead>Message</TableHead> */}
              {/* <TableHead className="text-center">Status</TableHead> */}
              <TableHead className="text-center">Created</TableHead>
              <TableHead className="text-center">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
                <TableCell colSpan={8} className="py-8 text-center">
                  Loading contacts...
                </TableCell>
              </TableRow>
            ) : contacts.length === 0 ? (
              <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
                <TableCell colSpan={8} className="py-8 text-center">
                  No contacts found.
                </TableCell>
              </TableRow>
            ) : (
              contacts.map((contact, index) => (
                <TableRow
                  key={contact._id}
                  className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
                >
                  <TableCell className="text-center">
                    {(page - 1) * limit + index + 1}
                  </TableCell>
                  <TableCell>{contact.name}</TableCell>
                  <TableCell>{contact.email}</TableCell>
                  <TableCell>{contact.phone}</TableCell>
                  {/* <TableCell>{contact.message.slice(0, 60)}{contact.message.length > 60 ? '...' : ''}</TableCell> */}
                  {/* <TableCell className="text-center">
                    <span className={`rounded-full px-2 py-1 text-xs font-medium ${contact.isRead ? 'bg-emerald-100 text-emerald-700' : 'bg-yellow-100 text-yellow-700'}`}>
                      {contact.isRead ? 'Read' : 'Unread'}
                    </span>
                  </TableCell> */}
                  <TableCell className="text-center">
                    {new Date(contact.createdAt).toLocaleDateString()}
                  </TableCell>
                  <TableCell className="space-x-1 text-center">
                    <Button
                      size="icon"
                      variant="outline"
                      onClick={() => openViewDialog(contact)}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button
                      size="icon"
                      variant="outline"
                      onClick={() => openEditDialog(contact)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      size="icon"
                      variant="outline"
                      onClick={() => handleDelete(contact._id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                    {/* <Button size="icon" variant="outline" onClick={() => handleToggleRead(contact)}>
                      <Check className="h-4 w-4" />
                    </Button> */}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* <div className="flex flex-wrap items-center justify-between gap-3 rounded-md border bg-white px-4 py-3 shadow-sm">
        <div>
          Showing {contacts.length} of {pagination.total} contacts
        </div>
        <div className="flex items-center gap-2">
          <Button size="sm" variant="default" onClick={() => handlePageChange(page - 1)} disabled={page <= 1}>
            <ArrowLeft className="mr-2 h-4 w-4" /> Prev
          </Button>
          <span>
            Page {pagination.page} of {pagination.pages || 1}
          </span>
          <Button size="sm" variant="default" onClick={() => handlePageChange(page + 1)} disabled={page >= pagination.pages}>
            Next <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div> */}

      {pagination.pages > 1 && (
        <div className="mt-4 flex items-center justify-between p-4">
          <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="default"
              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="default"
              size="sm"
              onClick={() => setPage(page + 1)}
              disabled={page === pagination.pages}
            >
              Next
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      <Dialog
        open={isDialogOpen}
        onOpenChange={(open) => {
          if (!open) closeDialog();
        }}
      >
        <DialogContent className="max-w-2xl">
          <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>
                  {isEditMode ? "Edit Contact" : "Create Contact"}
                </DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    closeDialog();
                    resetForm();
                  }}
                />
              </DialogHeader>
              <form
                className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2"
                onSubmit={handleSave}
              >
                <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                  <div>
                    <Label htmlFor="name">Name</Label>
                    <Input
                      id="name"
                      value={form.name}
                      onChange={(e) =>
                        setForm((prev) => ({ ...prev, name: e.target.value }))
                      }
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="email">Email</Label>
                    <Input
                      id="email"
                      type="email"
                      value={form.email}
                      onChange={(e) =>
                        setForm((prev) => ({ ...prev, email: e.target.value }))
                      }
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="phone">Phone</Label>
                    <Input
                      id="phone"
                      value={form.phone}
                      onChange={(e) =>
                        setForm((prev) => ({ ...prev, phone: e.target.value }))
                      }
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="message">Message</Label>
                    <Textarea
                      id="message"
                      value={form.message}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          message: e.target.value,
                        }))
                      }
                      rows={4}
                      required
                    />
                  </div>
                </div>
                <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                  <Button variant="outline" type="button" onClick={closeDialog}>
                    Cancel
                  </Button>
                  <Button type="submit" disabled={isSubmitting}>
                    {isSubmitting
                      ? "Saving..."
                      : isEditMode
                        ? "Update Contact"
                        : "Create Contact"}
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog
        open={isViewOpen}
        onOpenChange={(open) => {
          if (!open) setIsViewOpen(open);
        }}
      >
        <DialogContent className="max-w-2xl">
          <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Contact Details</DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsViewOpen(false);
                    resetForm();
                  }}
                />
              </DialogHeader>
              {viewingContact ? (
                <div className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2">
                  <div className="flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                    <div>
                      <p className="text-muted-foreground text-sm">Name</p>
                      <p className="font-medium">{viewingContact.name}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground text-sm">Email</p>
                      <p className="font-medium">{viewingContact.email}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground text-sm">Phone</p>
                      <p className="font-medium">{viewingContact.phone}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground text-sm">Message</p>
                      <p className="whitespace-pre-wrap">
                        {viewingContact.message}
                      </p>
                    </div>
                    <div className="grid gap-4 md:grid-cols-2">
                      <div>
                        <p className="text-muted-foreground text-sm">Status</p>
                        <p className="font-medium">
                          {viewingContact.isRead ? "Read" : "Unread"}
                        </p>
                      </div>
                      <div>
                        <p className="text-muted-foreground text-sm">
                          Created At
                        </p>
                        <p className="font-medium">
                          {new Date(viewingContact.createdAt).toLocaleString()}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="py-6 text-center">No contact selected.</div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default ContactManagement;
