"use client";

import { useState, useEffect } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../src/components/ui/table";
import { Badge } from "../../../../../src/components/ui/badge";
import { Eye, EyeOff, RefreshCw, User as UserIcon, Search, ChevronLeft, ChevronRight } from "lucide-react";
import { toast } from "sonner";
import { useDebounce } from "../../../../../src/hooks/useDebounce";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../../../../src/components/ui/dialog";
import { ArrowUpDown } from "lucide-react";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
interface Customer {
  _id: string;
  name: string;
  email: string;
  phone?: string;
  status: 'active' | 'inactive';
  createdAt: string;
}

export default function CustomersManagement() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  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 [pagination, setPagination] = useState({ total: 0, pages: 0, page: 1, limit: 10 });
  const [isViewOpen, setIsViewOpen] = useState(false);
  const [viewing, setViewing] = useState<Customer | null>(null);
  const [isResetOpen, setIsResetOpen] = useState(false);
  const [resetTarget, setResetTarget] = useState<{ id: string; name: string } | null>(null);
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [resetLoading, setResetLoading] = useState(false);
  const [sortBy, setSortBy] = useState("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  useEffect(() => { 
    fetchCustomers(); 
  }, [debouncedSearch, page, limit, sortBy, sortOrder]);

  const fetchCustomers = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({ 
        page: page.toString(), 
        limit: limit.toString(), 
        ...(debouncedSearch && { search: debouncedSearch }),
        sortBy,
        sortOrder
      });
      const res = await fetch(`/api/customers?${params}`);
      const data = await res.json();
      if (data.success) {
        setCustomers(data.data || []);
        setPagination(data.pagination || { total: 0, pages: 0, page, limit });
      } else {
        toast.error(data.error || 'Failed to load customers');
      }
    } catch (err) {
      console.error(err);
      toast.error('Error fetching customers');
    } finally {
      setLoading(false);
    }
  };

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

  const handleView = async (id: string) => {
    try {
      const res = await fetch(`/api/customers/${id}`);
      const data = await res.json();
      if (data.success) {
        setViewing(data.data);
        setIsViewOpen(true);
      } else {
        toast.error(data.error || 'Failed to fetch details');
      }
    } catch (err) {
      console.error(err);
      toast.error('Error fetching details');
    }
  };

  const openResetPasswordDialog = (id: string, name = '') => {
    setResetTarget({ id, name });
    setNewPassword('');
    setConfirmPassword('');
    setIsResetOpen(true);
  };

  const closeResetPasswordDialog = () => {
    setIsResetOpen(false);
    setResetTarget(null);
    setNewPassword('');
    setConfirmPassword('');
  };

  const handleResetPassword = async (id: string, name = '') => {
    openResetPasswordDialog(id, name);
  };

  const handleSubmitResetPassword = async () => {
    if (!resetTarget) return;
    if (!newPassword || !confirmPassword) {
      toast.error('Please enter both password fields');
      return;
    }
    if (newPassword.length < 6) {
      toast.error('Password must be at least 6 characters');
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error('Passwords do not match');
      return;
    }

    setResetLoading(true);
    try {
      const res = await fetch('/api/customers', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'resetPassword', id: resetTarget.id, newPassword })
      });
      const data = await res.json();
      if (data.success) {
        toast.success('Password updated successfully');
        closeResetPasswordDialog();
      } else {
        toast.error(data.error || 'Failed to reset password');
      }
    } catch (err) {
      console.error(err);
      toast.error('Error resetting password');
    } finally {
      setResetLoading(false);
    }
  };

  const handleToggleStatus = async (id: string, current: string) => {
    const next = current === 'active' ? 'inactive' : 'active';
    // if (!confirm(`Change status to ${next}?`)) return;
    try {
      const res = await fetch('/api/customers', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'setStatus', id, status: next })
      });
      const data = await res.json();
      if (data.success) {
        toast.success('Status updated');
        fetchCustomers();
      } else {
        toast.error(data.error || 'Failed to update status');
      }
    } catch (err) {
      console.error(err);
      toast.error('Error updating status');
    }
  };
  const handleSort = (field: string) => {
  if (sortBy === field) {
    setSortOrder(sortOrder === "asc" ? "desc" : "asc");
  } else {
    setSortBy(field);
    setSortOrder("asc");
  }

  setPage(1);
};

  return (
    <div className="space-y-6">
      <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 name, email or phone..." 
            value={search} 
            onChange={(e) => { 
              setSearch(e.target.value); 
              setPage(1); 
            }} 
            className="pl-10" 
          />
        </div>
        <div className="flex items-center gap-2">
          <select 
            value={limit.toString()} 
            onChange={(e) => { 
              setLimit(parseInt(e.target.value)); 
              setPage(1); 
            }} 
            className="px-3 py-2.5 rounded-md border"
          >
            <option value="6">6</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </div>
      </div>

      <div className="rounded-md border">
        <Table>
          <TableHeader className="dark:bg-gray-700">
            <TableRow>
             <TableHead
                className="text-center cursor-pointer select-none"
                onClick={() => handleSort("createdAt")}
                >
                <div className="flex items-center justify-center gap-1">
                    ID
                    <ArrowUpDown className="h-4 w-4" />
                </div>
                </TableHead>
                <TableHead
                className="text-left cursor-pointer select-none"
                onClick={() => handleSort("name")}
                >
                <div className="flex items-center gap-1">
                    Name
                    <ArrowUpDown className="h-4 w-4" />
                </div>
                </TableHead>
              <TableHead
                className="text-left cursor-pointer select-none"
                onClick={() => handleSort("email")}
                >
                <div className="flex items-center gap-1">
                    Email
                    <ArrowUpDown className="h-4 w-4" />
                </div>
                </TableHead>
              <TableHead className="text-left">Phone</TableHead>
              <TableHead className="text-center">Status</TableHead>
              <TableHead className="text-center">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className='dark:bg-gray-800'>
            {loading ? (
              <TableRow className="dark">
                <TableCell colSpan={6} className="text-center py-8">
                  <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>
            ) : customers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8">
                  No customers found
                </TableCell>
              </TableRow>
            ) : (
              customers.map((c, index) => (
                <TableRow key={c._id} className="hover:bg-gray-50 dark:hover:bg-gray-600">
                  <TableCell className="text-center">
                    {((page - 1) * limit) + index + 1}
                  </TableCell>
                  <TableCell>{c.name}</TableCell>
                  <TableCell>{c.email}</TableCell>
                  <TableCell>{c.phone || '-'}</TableCell>
                  <TableCell className="text-center">
                        <div className="flex items-center justify-center">
                            <button
                            type="button"
                            onClick={() => handleToggleStatus(c._id, c.status)}
                            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                                c.status === "active"
                                ? "bg-green-500"
                                : "bg-gray-300 dark:bg-gray-600"
                            }`}
                            >
                            <span
                                className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                                c.status === "active"
                                    ? "translate-x-6"
                                    : "translate-x-1"
                                }`}
                            />
                            </button>
                        </div>
                        </TableCell>
                  <TableCell className="text-center">
                    <div className="flex items-center justify-center gap-2">
                       
                      <Tooltip text='View'>
                        <Button size="sm" variant="outline" onClick={() => handleView(c._id)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                     
                      {/* <Tooltip text="Reset Password">
                        <Button size="sm" variant="outline" onClick={() => handleResetPassword(c._id, c.name)}>
                          <RefreshCw className="w-4 h-4"/>
                        </Button>
                      </Tooltip> */}
                      {/* <Button size="sm" variant="ghost" onClick={() => handleToggleStatus(c._id, c.status)}>
                        <UserIcon className="w-4 h-4"/>
                      </Button> */}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
      
      {/* Pagination */}
      {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} entries
          </div>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => handlePageChange(page - 1)}
              disabled={page === 1}
              className="rounded-lg border border-stroke px-3 py-2 text-sm font-medium text-black hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-strokedark dark:text-white"
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </button>
            {Array.from({ length: Math.min(pagination.pages, 5) }, (_, i) => {
              let pageNum;
              if (pagination.pages <= 5) {
                pageNum = i + 1;
              } else if (page <= 3) {
                pageNum = i + 1;
              } else if (page >= pagination.pages - 2) {
                pageNum = pagination.pages - 4 + i;
              } else {
                pageNum = page - 2 + i;
              }
              return (
                <button
                  key={pageNum}
                  onClick={() => handlePageChange(pageNum)}
                  className={`rounded-lg border px-3 py-2 text-sm font-medium ${
                    pageNum === page
                      ? 'border-primary bg-primary text-white'
                      : 'border-stroke text-black hover:bg-gray-50 dark:border-strokedark dark:text-white'
                  }`}
                >
                  {pageNum}
                </button>
              );
            })}
            <button
              onClick={() => handlePageChange(page + 1)}
              disabled={page === pagination.pages}
              className="rounded-lg border border-stroke px-3 py-2 text-sm font-medium text-black hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-strokedark dark:text-white"
            >
              Next
              <ChevronRight className="h-4 w-4 ml-1" />
            </button>
          </div>
        </div>
      )}

     {/* View Dialog */}
<Dialog open={isViewOpen} onOpenChange={setIsViewOpen}>
  <DialogContent className="max-w-2xl">
    <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>Customer Details</DialogTitle>

          <button
            onClick={() => setIsViewOpen(false)}
            className="absolute right-4 top-4"
          >
            ✕
          </button>
        </DialogHeader>

        {viewing ? (
          <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="space-y-6 pb-4">

                {/* User Icon */}
                <div className="flex justify-center">
                  <div className="h-24 w-24 rounded-full bg-gray-100 dark:bg-[#324153] flex items-center justify-center border">
                    <UserIcon className="h-12 w-12 text-gray-500" />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">

                  <div className="space-y-1">
                    <label className="text-xs text-gray-500">
                      Name
                    </label>

                    <p className="text-sm font-medium break-words">
                      {viewing.name}
                    </p>
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs text-gray-500">
                      Email
                    </label>

                    <p className="text-sm font-medium break-all">
                      {viewing.email}
                    </p>
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs text-gray-500">
                      Phone
                    </label>

                    <p className="text-sm font-medium">
                      {viewing.phone || "-"}
                    </p>
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs text-gray-500">
                      Status
                    </label>

                    <div>
                      <Badge
                        variant={
                          viewing.status === "active"
                            ? "default"
                            : "secondary"
                        }
                        className="mt-1"
                      >
                        {viewing.status}
                      </Badge>
                    </div>
                  </div>

                  <div className="col-span-2 pt-3 border-t">
                    <div className="grid grid-cols-2 gap-4">

                      <div className="space-y-1">
                        <label className="text-xs text-gray-500">
                          Created At
                        </label>

                        <p className="text-xs text-gray-500">
                          {new Date(viewing.createdAt).toLocaleString()}
                        </p>
                      </div>

                    </div>
                  </div>

                </div>
              </div>
            </div>

            {/* Footer */}
            <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);
                  handleResetPassword(viewing._id, viewing.name);
                }}
              >
                <RefreshCw className="w-4 h-4 mr-1" />
                Reset Password
              </Button>

              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setIsViewOpen(false);
                  handleToggleStatus(viewing._id, viewing.status);
                }}
              >
                <UserIcon className="w-4 h-4 mr-1" />
                {viewing.status === "active"
                  ? "Deactivate"
                  : "Activate"}
              </Button>

            </div>

          </div>
        ) : (
          <div className="py-10 text-center">
            Loading...
          </div>
        )}
      </div>
    </div>
  </DialogContent>
</Dialog>

<Dialog open={isResetOpen} onOpenChange={(open) => { if (!open) closeResetPasswordDialog(); }}>
  <DialogContent className="max-w-lg">
    <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>Reset Customer Password</DialogTitle>

          <button
            onClick={closeResetPasswordDialog}
            className="absolute right-4 top-4"
          >
            ✕
          </button>
        </DialogHeader>

        <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
          <div className="max-h-[60vh] min-h-[40vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
            <div className="space-y-4">
              <p className="text-sm text-gray-600 dark:text-gray-300">
                Enter a new password for <span className="font-semibold text-gray-900 dark:text-white">{resetTarget?.name || 'customer'}</span>.
              </p>
              <div className="space-y-2">
                <label className="text-xs text-gray-500">New Password</label>
                <div className="relative">
                  <Input
                    type={showNewPassword ? 'text' : 'password'}
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    placeholder="New password"
                    className="pr-10"
                  />
                  <button
                    type="button"
                    onClick={() => setShowNewPassword((prev) => !prev)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                  >
                    {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-xs text-gray-500">Confirm Password</label>
                <div className="relative">
                  <Input
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    placeholder="Confirm password"
                    className="pr-10"
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword((prev) => !prev)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                  >
                    {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              <p className="text-xs text-gray-500">
                Password must be at least 6 characters and match the confirmation field.
              </p>
            </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={closeResetPasswordDialog}>
              Cancel
            </Button>
            <Button size="sm" onClick={handleSubmitResetPassword} disabled={resetLoading}>
              {resetLoading ? 'Saving...' : 'Save Password'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  </DialogContent>
</Dialog>
    </div>
  );
}