"use client";

import { useState, useEffect, type FormEvent } from "react";
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,
  X,
  ChevronLeft,
  ChevronRight,
  Plus,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
} from "lucide-react";
import { toast } from "sonner";
import { useDebounce } from "../../../../../src/hooks/useDebounce";

interface Inquiry {
  _id: string;
  firstName: string;
  lastName?: string;
  email: string;
  mobile: string;
  feedback?: string;
  state?: { _id: string; name: string } | string;
  createdAt: string;
}

type SortField = "firstName" | "email" | "mobile" | "state" | "createdAt";
type SortOrder = "asc" | "desc";

export default function InquiriesManagement() {
  const [items, setItems] = useState<Inquiry[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 400);

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [sortField, setSortField] = useState<SortField>("createdAt");
  const [sortOrder, setSortOrder] = useState<SortOrder>("desc");

  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    page: 1,
    limit: 10,
  });

  const [states, setStates] = useState<{ _id: string; name: string }[]>([]);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [form, setForm] = useState({
    firstName: "",
    lastName: "",
    email: "",
    mobile: "",
    state: "",
    feedback: "",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const [isViewOpen, setIsViewOpen] = useState(false);
  const [viewing, setViewing] = useState<Inquiry | null>(null);

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

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

  const fetchStates = async () => {
    try {
      const res = await fetch("/api/states");
      const data = await res.json();
      if (data.success) {
        setStates(data.data || []);
      } else {
        toast.error(data.error || "Failed to load states");
      }
    } catch (err) {
      console.error(err);
      toast.error("Error fetching states");
    }
  };

  const fetchItems = async (pageNumber = page) => {
    try {
      setLoading(true);

      const params = new URLSearchParams({
        page: pageNumber.toString(),
        limit: limit.toString(),
        sortField: sortField,
        sortOrder: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch }),
      });

      const res = await fetch(`/api/inquiries?${params}`);
      const data = await res.json();

      if (data.success) {
        setItems(data.data || []);
        setPagination(
          data.pagination || {
            total: 0,
            pages: 0,
            page,
            limit,
          },
        );
      } else {
        toast.error(data.error || "Failed to load inquiries");
      }
    } catch (err) {
      console.error(err);
      toast.error("Error fetching inquiries");
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setForm({
      firstName: "",
      lastName: "",
      email: "",
      mobile: "",
      state: "",
      feedback: "",
    });
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!form.firstName.trim() || !form.email.trim() || !form.mobile.trim()) {
      toast.error("First name, email, and mobile are required.");
      return;
    }

    try {
      setIsSubmitting(true);
      const res = await fetch("/api/inquiries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          firstName: form.firstName.trim(),
          lastName: form.lastName.trim(),
          email: form.email.trim(),
          mobile: form.mobile.trim(),
          state: form.state || undefined,
          feedback: form.feedback.trim(),
        }),
      });

      const data = await res.json();
      if (!data.success) {
        toast.error(data.error || "Failed to create inquiry.");
        return;
      }

      toast.success("Inquiry added successfully");
      setIsAddOpen(false);
      resetForm();
      const nextPage = 1;
      setPage(nextPage);
      await fetchItems(nextPage);
    } catch (err) {
      console.error(err);
      toast.error("Error saving inquiry.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handlePageChange = (newPage: number) => {
    setPage(newPage);
  };

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      // Toggle order if same field
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      // New field, default to ascending
      setSortField(field);
      setSortOrder("asc");
    }
    setPage(1); // Reset to first page when sorting changes
  };

  const getSortIcon = (field: SortField) => {
    if (sortField !== field) {
      return <ArrowUpDown className="ml-1 h-4 w-4" />;
    }
    return sortOrder === "asc" ? (
      <ArrowUp className="ml-1 h-4 w-4" />
    ) : (
      <ArrowDown className="ml-1 h-4 w-4" />
    );
  };

  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">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div className="flex min-w-0 flex-1 items-center gap-4">
          <div className="relative max-w-sm flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <Input
              placeholder="Search by name, email, mobile or order..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
              className="pl-10"
            />
          </div>

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

        <Dialog
          open={isAddOpen}
          onOpenChange={(open) => {
            setIsAddOpen(open);
            if (!open) resetForm();
          }}
        >
          <DialogTrigger asChild>
            {/* <Button className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              Add Inquiry
            </Button> */}
          </DialogTrigger>

          <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 rounded-lg border border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                <DialogHeader className="flex flex-shrink-0 items-center justify-between gap-2 p-4">
                  <DialogTitle>Add Inquiry</DialogTitle>
                  <Button
                    variant="ghost"
                    onClick={() => setIsAddOpen(false)}
                    className="h-9 w-9 rounded-full p-0"
                  >
                    ×
                  </Button>
                </DialogHeader>
                <form
                  onSubmit={handleSubmit}
                  className="flex flex-col gap-4 p-4"
                >
                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div>
                      <Label htmlFor="firstName">First Name</Label>
                      <Input
                        id="firstName"
                        value={form.firstName}
                        onChange={(e) =>
                          setForm({ ...form, firstName: e.target.value })
                        }
                        required
                      />
                    </div>

                    <div>
                      <Label htmlFor="lastName">Last Name</Label>
                      <Input
                        id="lastName"
                        value={form.lastName}
                        onChange={(e) =>
                          setForm({ ...form, lastName: e.target.value })
                        }
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div>
                      <Label htmlFor="email">Email</Label>
                      <Input
                        id="email"
                        type="email"
                        value={form.email}
                        onChange={(e) =>
                          setForm({ ...form, email: e.target.value })
                        }
                        required
                      />
                    </div>

                    <div>
                      <Label htmlFor="mobile">Mobile</Label>
                      <Input
                        id="mobile"
                        value={form.mobile}
                        onChange={(e) =>
                          setForm({ ...form, mobile: e.target.value })
                        }
                        required
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div>
                      <Label htmlFor="state">State</Label>
                      <select
                        id="state"
                        value={form.state}
                        onChange={(e) =>
                          setForm({ ...form, state: e.target.value })
                        }
                        className="w-full rounded-md border px-3 py-2.5 text-sm"
                      >
                        <option value="">Select state</option>
                        {states.map((state) => (
                          <option key={state._id} value={state._id}>
                            {state.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="feedback">Feedback</Label>
                    <Textarea
                      id="feedback"
                      value={form.feedback}
                      onChange={(e) =>
                        setForm({ ...form, feedback: e.target.value })
                      }
                    />
                  </div>

                  <div className="flex justify-end gap-3 pt-2">
                    <Button
                      type="button"
                      variant="secondary"
                      onClick={() => setIsAddOpen(false)}
                    >
                      Cancel
                    </Button>
                    <Button type="submit" disabled={isSubmitting}>
                      {isSubmitting ? "Saving..." : "Save Inquiry"}
                    </Button>
                  </div>
                </form>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="rounded-md border">
        <Table>
          <TableHeader className="dark:bg-gray-800">
            <TableRow>
              <TableHead className="text-center">#</TableHead>
              <TableHead
                className="cursor-pointer transition-colors hover:bg-gray-200 dark:hover:bg-gray-600"
                onClick={() => handleSort("firstName")}
              >
                <div className="flex items-center gap-1">
                  Name
                  {getSortIcon("firstName")}
                </div>
              </TableHead>
              <TableHead
                className="cursor-pointer transition-colors hover:bg-gray-200 dark:hover:bg-gray-600"
                onClick={() => handleSort("email")}
              >
                <div className="flex items-center gap-1">
                  Email
                  {getSortIcon("email")}
                </div>
              </TableHead>
              <TableHead
                className="cursor-pointer transition-colors hover:bg-gray-200 dark:hover:bg-gray-600"
                onClick={() => handleSort("mobile")}
              >
                <div className="flex items-center gap-1">
                  Mobile
                  {getSortIcon("mobile")}
                </div>
              </TableHead>
              <TableHead
                className="cursor-pointer transition-colors hover:bg-gray-200 dark:hover:bg-gray-600"
                onClick={() => handleSort("state")}
              >
                <div className="flex items-center gap-1">
                  State
                  {getSortIcon("state")}
                </div>
              </TableHead>
              <TableHead
                className="cursor-pointer text-center transition-colors hover:bg-gray-200 dark:hover:bg-gray-600"
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-1">
                  Created At
                  {getSortIcon("createdAt")}
                </div>
              </TableHead>
              <TableHead className="text-center">Actions</TableHead>
            </TableRow>
          </TableHeader>

          <TableBody className="dark:bg-gray-800">
            {loading ? (
              <TableRow>
                <TableCell colSpan={7} className="py-8 text-center">
                  Loading...
                </TableCell>
              </TableRow>
            ) : items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="py-8 text-center">
                  No inquiries found
                </TableCell>
              </TableRow>
            ) : (
              items.map((it, index) => (
                <TableRow key={it._id}>
                  <TableCell className="text-center">
                    {(page - 1) * limit + index + 1}
                  </TableCell>
                  <TableCell>
                    {it.firstName} {it.lastName}
                  </TableCell>
                  <TableCell>{it.email}</TableCell>
                  <TableCell>{it.mobile}</TableCell>
                  <TableCell>
                    {typeof it.state === "string"
                      ? it.state
                      : it.state?.name || "-"}
                  </TableCell>
                  <TableCell className="text-center">
                    {formatDate(it.createdAt)}
                  </TableCell>
                  <TableCell className="text-center">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setViewing(it);
                        setIsViewOpen(true);
                      }}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <Dialog
        open={isViewOpen}
        onOpenChange={(open) => {
          setIsViewOpen(open);
          if (!open) setViewing(null);
        }}
      >
        <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 rounded-lg border border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader className="flex flex-shrink-0 items-center justify-between gap-2 p-4">
                <DialogTitle>Inquiry Details</DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsViewOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="space-y-4 p-4">
                <div>
                  <span className="font-semibold">Name:</span>{" "}
                  {viewing?.firstName} {viewing?.lastName || ""}
                </div>
                <div>
                  <span className="font-semibold">Email:</span> {viewing?.email}
                </div>
                <div>
                  <span className="font-semibold">Mobile:</span>{" "}
                  {viewing?.mobile}
                </div>
                <div>
                  <span className="font-semibold">State:</span>{" "}
                  {typeof viewing?.state === "string"
                    ? viewing.state
                    : viewing?.state?.name || "-"}
                </div>
                <div>
                  <span className="font-semibold">Feedback:</span>
                  <p className="mt-1 w-100 break-words rounded-md border bg-gray-50 p-3 text-sm dark:bg-gray-900">
                    {viewing?.feedback || "-"}
                  </p>
                </div>
                <div>
                  <span className="font-semibold">Created At:</span>{" "}
                  {viewing ? formatDate(viewing.createdAt) : "-"}
                </div>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {pagination.pages > 1 && (
        <div className="mt-4 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}
          </div>

          <div className="flex items-center gap-2">
            <Button
              variant="default"
              onClick={() => handlePageChange(page - 1)}
              disabled={page === 1}
              className="rounded border px-3 py-2 disabled:opacity-50"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>

            <span className="text-sm">
              Page {page} of {pagination.pages}
            </span>

            <Button
              variant="default"
              onClick={() => handlePageChange(page + 1)}
              disabled={page === pagination.pages}
              className="rounded border px-3 py-2 disabled:opacity-50"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
