"use client";

import { useEffect, useState } from "react";
import {
  Mail,
  Phone,
  Building,
  MessageSquare,
  Search,
  X,
  User,
  Clock,
  Languages,
  FileText,
  Trash2,
  AlertTriangle,
} from "lucide-react";

interface Contact {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  company: string | null;
  message: string;
  language: string;
  status: string;
  createdAt: string;
  updatedAt: string;
  respondedAt: string | null;
  respondedBy: string | null;
  internalNotes: string | null;
  assignedTo: string | null;
  assignedStaff?: {
    id: string;
    name: string;
    email: string;
  } | null;
}

interface User {
  id: string;
  role: string;
}

export default function ContactsList({ user }: { user: User }) {
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState({
    status: "all",
    search: "",
  });
  const [selectedContact, setSelectedContact] = useState<Contact | null>(null);
  const [editingNotes, setEditingNotes] = useState<string | null>(null);
  const [notesText, setNotesText] = useState("");
  const [deletingContact, setDeletingContact] = useState<string | null>(null);
  const [showDeleteAllModal, setShowDeleteAllModal] = useState(false);
  const [deleteAllConfirmation, setDeleteAllConfirmation] = useState("");
  const [deleting, setDeleting] = useState(false);
  const [toast, setToast] = useState<{
    message: string;
    type: "success" | "error";
  } | null>(null);

  const fetchContacts = async () => {
    try {
      const params = new URLSearchParams();
      if (filter.status !== "all") params.append("status", filter.status);
      if (filter.search) params.append("search", filter.search);

      const response = await fetch(`/api/staff/dashboard/contacts?${params}`);
      if (response.ok) {
        const data = await response.json();
        setContacts(data.contacts);
      }
    } catch (error) {
      console.error("Failed to fetch contacts:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContacts();
  }, [filter]);

  const handleStatusUpdate = async (contactId: string, newStatus: string) => {
    try {
      const response = await fetch("/api/staff/dashboard/contacts/update", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ contactId, status: newStatus }),
      });

      if (response.ok) {
        fetchContacts();
      }
    } catch (error) {
      console.error("Failed to update status:", error);
    }
  };

  const handleDeleteContact = async (contactId: string) => {
    try {
      setDeleting(true);
      const response = await fetch(
        `/api/staff/dashboard/contacts/delete?id=${contactId}`,
        {
          method: "DELETE",
        },
      );

      if (response.ok) {
        setToast({ message: "Contact deleted successfully", type: "success" });
        setDeletingContact(null);
        fetchContacts();
      } else {
        const data = await response.json();
        setToast({
          message: data.error || "Failed to delete contact",
          type: "error",
        });
      }
    } catch (error) {
      console.error("Failed to delete contact:", error);
      setToast({ message: "Failed to delete contact", type: "error" });
    } finally {
      setDeleting(false);
    }
  };

  const handleDeleteAll = async () => {
    try {
      setDeleting(true);
      const response = await fetch("/api/staff/dashboard/contacts/delete-all", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ confirmationToken: deleteAllConfirmation }),
      });

      if (response.ok) {
        const data = await response.json();
        setToast({
          message: data.message || "All contacts deleted successfully",
          type: "success",
        });
        setShowDeleteAllModal(false);
        setDeleteAllConfirmation("");
        fetchContacts();
      } else {
        const data = await response.json();
        setToast({
          message: data.error || "Failed to delete contacts",
          type: "error",
        });
      }
    } catch (error) {
      console.error("Failed to delete all contacts:", error);
      setToast({ message: "Failed to delete all contacts", type: "error" });
    } finally {
      setDeleting(false);
    }
  };

  // Auto-dismiss toast after 5 seconds
  useEffect(() => {
    if (toast) {
      const timer = setTimeout(() => setToast(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [toast]);

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      NEW: "bg-blue-100 text-blue-800",
      READ: "bg-gray-100 text-gray-800",
      IN_PROGRESS: "bg-yellow-100 text-yellow-800",
      RESPONDED: "bg-green-100 text-green-800",
      CLOSED: "bg-gray-100 text-gray-600",
    };

    return (
      <span
        className={`px-2 py-1 rounded-full text-xs font-semibold ${styles[status] || "bg-gray-100 text-gray-800"}`}
      >
        {status.replace("_", " ")}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading contacts...</p>
        </div>
      </div>
    );
  }

  // Calculate statistics
  const stats = {
    total: contacts.length,
    new: contacts.filter((c) => c.status === "NEW").length,
    inProgress: contacts.filter((c) => c.status === "IN_PROGRESS").length,
    responded: contacts.filter((c) => c.status === "RESPONDED").length,
    unassigned: contacts.filter((c) => !c.assignedTo).length,
  };

  return (
    <div className="space-y-4">
      {/* Toast Notification */}
      {toast && (
        <div
          className={`fixed top-4 right-4 z-50 px-6 py-4 rounded-lg shadow-lg border ${
            toast.type === "success"
              ? "bg-green-50 border-green-200 text-green-800"
              : "bg-red-50 border-red-200 text-red-800"
          } animate-fade-in`}
        >
          <div className="flex items-center gap-3">
            {toast.type === "success" ? (
              <div className="w-5 h-5 rounded-full bg-green-500 flex items-center justify-center">
                <svg
                  className="w-3 h-3 text-white"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M5 13l4 4L19 7"
                  />
                </svg>
              </div>
            ) : (
              <AlertTriangle className="w-5 h-5" />
            )}
            <span className="font-medium">{toast.message}</span>
            <button type="button" aria-label="Dismiss" onClick={() => setToast(null)} className="ml-4">
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Statistics Summary */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
          <p className="text-xs font-medium text-gray-500 uppercase mb-1">
            Total
          </p>
          <p className="text-2xl font-bold text-brand-ink">{stats.total}</p>
        </div>
        <div className="bg-blue-50 rounded-xl shadow-sm border border-blue-200 p-4">
          <p className="text-xs font-medium text-blue-700 uppercase mb-1">
            New
          </p>
          <p className="text-2xl font-bold text-blue-700">{stats.new}</p>
        </div>
        <div className="bg-yellow-50 rounded-xl shadow-sm border border-yellow-200 p-4">
          <p className="text-xs font-medium text-yellow-700 uppercase mb-1">
            In Progress
          </p>
          <p className="text-2xl font-bold text-yellow-700">
            {stats.inProgress}
          </p>
        </div>
        <div className="bg-green-50 rounded-xl shadow-sm border border-green-200 p-4">
          <p className="text-xs font-medium text-green-700 uppercase mb-1">
            Responded
          </p>
          <p className="text-2xl font-bold text-green-700">{stats.responded}</p>
        </div>
        <div className="bg-orange-50 rounded-xl shadow-sm border border-orange-200 p-4">
          <p className="text-xs font-medium text-orange-700 uppercase mb-1">
            Unassigned
          </p>
          <p className="text-2xl font-bold text-orange-700">
            {stats.unassigned}
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search by name or email..."
              value={filter.search}
              onChange={(e) => setFilter({ ...filter, search: e.target.value })}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
            />
          </div>

          <select
            value={filter.status}
            onChange={(e) => setFilter({ ...filter, status: e.target.value })}
            className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
          >
            <option value="all">All Status</option>
            <option value="NEW">New</option>
            <option value="READ">Read</option>
            <option value="IN_PROGRESS">In Progress</option>
            <option value="RESPONDED">Responded</option>
            <option value="CLOSED">Closed</option>
          </select>

          <button
            onClick={() => setFilter({ status: "all", search: "" })}
            className="flex items-center justify-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
          >
            <X className="w-4 h-4" />
            Clear
          </button>
        </div>
      </div>

      {/* Danger Zone - Delete All */}
      {(user.role === "ADMIN" || user.role === "SUPER_ADMIN") &&
        contacts.length > 0 && (
          <div className="bg-red-50 border-2 border-red-200 rounded-xl p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <AlertTriangle className="w-5 h-5 text-red-600" />
                <div>
                  <h3 className="font-semibold text-red-900">Danger Zone</h3>
                  <p className="text-sm text-red-700">
                    Permanently delete all contact submissions
                  </p>
                </div>
              </div>
              <button
                onClick={() => setShowDeleteAllModal(true)}
                className="px-4 py-2 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 transition flex items-center gap-2"
              >
                <Trash2 className="w-4 h-4" />
                Delete All Contacts
              </button>
            </div>
          </div>
        )}

      {/* Results */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-600">
          {contacts.length} contact{contacts.length !== 1 ? "s" : ""} found
        </p>
        <button
          onClick={fetchContacts}
          className="text-sm text-brand-green hover:underline"
        >
          Refresh
        </button>
      </div>

      {/* Contacts List */}
      <div className="space-y-4">
        {contacts.length > 0 ? (
          contacts.map((contact) => (
            <div
              key={contact.id}
              className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="text-lg font-semibold text-brand-ink">
                      {contact.name}
                    </h3>
                    {getStatusBadge(contact.status)}
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-1 text-sm text-gray-600 mb-3">
                    <div className="flex items-center gap-2">
                      <Mail className="w-4 h-4" />
                      <a
                        href={`mailto:${contact.email}`}
                        className="hover:text-brand-green"
                      >
                        {contact.email}
                      </a>
                    </div>
                    {contact.phone && (
                      <div className="flex items-center gap-2">
                        <Phone className="w-4 h-4" />
                        <a
                          href={`tel:${contact.phone}`}
                          className="hover:text-brand-green"
                        >
                          {contact.phone}
                        </a>
                      </div>
                    )}
                    {contact.company && (
                      <div className="flex items-center gap-2">
                        <Building className="w-4 h-4" />
                        {contact.company}
                      </div>
                    )}
                    <div className="flex items-center gap-2">
                      <Languages className="w-4 h-4" />
                      <span className="uppercase font-medium">
                        {contact.language}
                      </span>
                    </div>
                    {contact.assignedStaff && (
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-brand-green" />
                        <span className="text-brand-green font-medium">
                          Assigned: {contact.assignedStaff.name}
                        </span>
                      </div>
                    )}
                  </div>
                  <div className="p-4 bg-gray-50 rounded-lg mb-3">
                    <p className="text-xs font-medium text-gray-700 mb-2">
                      Message:
                    </p>
                    <p className="text-sm text-gray-800 whitespace-pre-wrap">
                      {contact.message}
                    </p>
                  </div>
                  {contact.internalNotes && editingNotes !== contact.id && (
                    <div className="p-4 bg-amber-50 border border-amber-200 rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                          <FileText className="w-4 h-4 text-amber-700" />
                          <p className="text-xs font-medium text-amber-700">
                            Internal Notes:
                          </p>
                        </div>
                        <button
                          onClick={() => {
                            setEditingNotes(contact.id);
                            setNotesText(contact.internalNotes || "");
                          }}
                          className="text-xs text-amber-700 hover:text-amber-900 underline"
                        >
                          Edit
                        </button>
                      </div>
                      <p className="text-sm text-amber-900 whitespace-pre-wrap">
                        {contact.internalNotes}
                      </p>
                    </div>
                  )}

                  {/* Notes Editor */}
                  {editingNotes === contact.id && (
                    <div className="p-4 bg-amber-50 border-2 border-amber-300 rounded-lg">
                      <div className="flex items-center gap-2 mb-2">
                        <FileText className="w-4 h-4 text-amber-700" />
                        <p className="text-xs font-medium text-amber-700">
                          Internal Notes:
                        </p>
                      </div>
                      <textarea
                        value={notesText}
                        onChange={(e) => setNotesText(e.target.value)}
                        className="w-full p-3 border border-amber-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent text-sm"
                        rows={4}
                        placeholder="Add internal notes (only visible to staff)..."
                      />
                      <div className="flex gap-2 mt-2">
                        <button
                          onClick={async () => {
                            try {
                              const response = await fetch(
                                "/api/staff/dashboard/contacts/update",
                                {
                                  method: "POST",
                                  headers: {
                                    "Content-Type": "application/json",
                                  },
                                  body: JSON.stringify({
                                    contactId: contact.id,
                                    internalNotes: notesText,
                                  }),
                                },
                              );
                              if (response.ok) {
                                setEditingNotes(null);
                                fetchContacts();
                              }
                            } catch (error) {
                              console.error("Failed to update notes:", error);
                            }
                          }}
                          className="px-3 py-1.5 bg-amber-600 text-white text-xs font-medium rounded-lg hover:bg-amber-700"
                        >
                          Save Notes
                        </button>
                        <button
                          onClick={() => {
                            setEditingNotes(null);
                            setNotesText("");
                          }}
                          className="px-3 py-1.5 border border-amber-300 text-amber-700 text-xs font-medium rounded-lg hover:bg-amber-100"
                        >
                          Cancel
                        </button>
                      </div>
                    </div>
                  )}

                  {/* Add Notes Button (if no notes exist) */}
                  {!contact.internalNotes && editingNotes !== contact.id && (
                    <button
                      onClick={() => {
                        setEditingNotes(contact.id);
                        setNotesText("");
                      }}
                      className="flex items-center gap-2 px-4 py-2 border border-dashed border-amber-300 text-amber-700 text-sm rounded-lg hover:bg-amber-50 transition w-full justify-center"
                    >
                      <FileText className="w-4 h-4" />
                      Add Internal Notes
                    </button>
                  )}
                </div>

                {/* Actions */}
                <div className="flex flex-col gap-2 ml-4">
                  {contact.status === "NEW" && (
                    <button
                      onClick={() => handleStatusUpdate(contact.id, "READ")}
                      className="px-4 py-2 bg-gray-600 text-white text-sm rounded-lg hover:bg-gray-700"
                    >
                      Mark Read
                    </button>
                  )}
                  {contact.status !== "RESPONDED" &&
                    contact.status !== "CLOSED" && (
                      <button
                        onClick={() =>
                          handleStatusUpdate(contact.id, "IN_PROGRESS")
                        }
                        className="px-4 py-2 bg-yellow-600 text-white text-sm rounded-lg hover:bg-yellow-700"
                      >
                        In Progress
                      </button>
                    )}
                  <button
                    onClick={() => handleStatusUpdate(contact.id, "RESPONDED")}
                    className="px-4 py-2 bg-brand-green text-white text-sm rounded-lg hover:bg-green-700"
                  >
                    Responded
                  </button>
                  <a
                    href={`mailto:${contact.email}`}
                    className="px-4 py-2 border border-gray-300 text-gray-700 text-sm text-center rounded-lg hover:bg-gray-50"
                  >
                    Reply
                  </a>
                  <button
                    onClick={() => setDeletingContact(contact.id)}
                    className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 flex items-center justify-center gap-2"
                  >
                    <Trash2 className="w-4 h-4" />
                    Delete
                  </button>
                </div>
              </div>

              <div className="mt-4 pt-4 border-t border-gray-200">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs text-gray-500">
                  <div className="flex items-center gap-2">
                    <Clock className="w-3 h-3" />
                    <span>
                      Submitted: {new Date(contact.createdAt).toLocaleString()}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Clock className="w-3 h-3" />
                    <span>
                      Last Updated:{" "}
                      {new Date(contact.updatedAt).toLocaleString()}
                    </span>
                  </div>
                  {contact.respondedAt && (
                    <div className="flex items-center gap-2 text-green-600">
                      <Clock className="w-3 h-3" />
                      <span>
                        Responded:{" "}
                        {new Date(contact.respondedAt).toLocaleString()}
                      </span>
                    </div>
                  )}
                  {contact.respondedBy && (
                    <div className="flex items-center gap-2 text-green-600">
                      <User className="w-3 h-3" />
                      <span>
                        Responded By: Staff ID{" "}
                        {contact.respondedBy.substring(0, 8)}...
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))
        ) : (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
            <MessageSquare className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              No contacts found
            </h3>
            <p className="text-gray-600">
              {filter.status !== "all" || filter.search
                ? "Try adjusting your filters"
                : "No contact messages yet"}
            </p>
          </div>
        )}
      </div>

      {/* Delete Contact Confirmation Modal */}
      {deletingContact && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center">
                <Trash2 className="w-6 h-6 text-red-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900">
                Delete Contact
              </h3>
            </div>
            <p className="text-gray-600 mb-6">
              Are you sure you want to delete this contact? This action cannot
              be undone.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => handleDeleteContact(deletingContact)}
                disabled={deleting}
                className="flex-1 px-4 py-2 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {deleting ? "Deleting..." : "Delete"}
              </button>
              <button
                onClick={() => setDeletingContact(null)}
                disabled={deleting}
                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 disabled:opacity-50"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete All Contacts Modal */}
      {showDeleteAllModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-lg w-full p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center">
                <AlertTriangle className="w-6 h-6 text-red-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900">
                Delete All Contacts
              </h3>
            </div>

            <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
              <p className="text-red-900 font-semibold mb-2">
                DANGER: This action is irreversible!
              </p>
              <p className="text-red-800 text-sm">
                You are about to permanently delete{" "}
                <span className="font-bold">{contacts.length}</span> contact
                submission(s). All data including messages, notes, and history
                will be lost forever.
              </p>
            </div>

            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Type{" "}
                <span className="font-mono bg-gray-100 px-2 py-1 rounded">
                  DELETE ALL
                </span>{" "}
                to confirm:
              </label>
              <input
                type="text"
                value={deleteAllConfirmation}
                onChange={(e) => setDeleteAllConfirmation(e.target.value)}
                placeholder="Type DELETE ALL"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent"
              />
            </div>

            <div className="flex gap-3">
              <button
                onClick={handleDeleteAll}
                disabled={deleteAllConfirmation !== "DELETE ALL" || deleting}
                className="flex-1 px-4 py-2 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {deleting ? "Deleting..." : "Delete All Contacts"}
              </button>
              <button
                onClick={() => {
                  setShowDeleteAllModal(false);
                  setDeleteAllConfirmation("");
                }}
                disabled={deleting}
                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 disabled:opacity-50"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
