"use client";

import { useState, useEffect, useRef } from "react";
import { toast } from "react-hot-toast";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "../../../../../../src/components/ui/dialog";
import {
  Plus,
  Edit,
  Trash2,
  Search,
  ChevronLeft,
  ChevronRight as ChevronRightIcon,
  Eye,
  X,
  ArrowUpDown,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../../src/components/ui/table";
import { Button } from "../../../../../../src/components/ui/button";
import { Label } from "@radix-ui/react-label";
import { Input } from "../../../../../../src/components/ui/input";
import { Textarea } from "../../../../../../src/components/ui/textarea";
import { Badge } from "../../../../../../src/components/ui/badge";
import { Tooltip } from "../../../../../../src/components/ui/tooltip";

interface StaticVideo {
  _id: string;
  title: string;
  subtitle: string;
  video_url: string;
  status: boolean;
  createdAt: string;
  updatedAt: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  pages: number;
}

const StaticVideoManagement = () => {
  const [videos, setVideos] = useState<StaticVideo[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [sortField, setSortField] = useState<"createdAt" | "title" | "status">(
    "createdAt",
  );
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0,
  });
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedVideo, setSelectedVideo] = useState<StaticVideo | null>(null);
  const [viewingVideo, setViewingVideo] = useState<StaticVideo | null>(null);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);

  const [formData, setFormData] = useState({
    title: "",
    subtitle: "",
    status: true,
    video_file: null as File | null,
  });

  const fileInputRef = useRef<HTMLInputElement>(null);
  const editFileInputRef = useRef<HTMLInputElement>(null);

  const formatDate = (dateString: string) =>
    new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

  const fetchVideos = async (
    page = 1,
    search = "",
    status = "all",
    sort = sortField,
    order = sortOrder,
  ) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        sort,
        order,
        ...(search && { search }),
        ...(status !== "all" && { status }),
      });
      const response = await fetch(`/api/static-videos?${params}`);
      const data = await response.json();
      if (data.success) {
        setVideos(data.data);
        setPagination(data.pagination);
      } else {
        toast.error(data.error || "Failed to fetch videos");
      }
    } catch (error) {
      console.error("Error fetching videos:", error);
      toast.error("Failed to fetch videos");
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      fetchVideos(1, searchTerm, statusFilter, sortField, sortOrder);
    }, 500);
    return () => clearTimeout(timeoutId);
  }, [searchTerm, statusFilter, sortField, sortOrder]);

  const handleLimitChange = (value: string) => {
    const newLimit = parseInt(value, 10) || 10;
    setPagination((prev) => ({ ...prev, limit: newLimit, page: 1 }));
    fetchVideos(1, searchTerm, statusFilter, sortField, sortOrder);
  };

  const handleSort = (field: "createdAt" | "title" | "status") => {
    const newOrder =
      sortField === field && sortOrder === "asc" ? "desc" : "asc";
    setSortField(field);
    setSortOrder(newOrder);
    fetchVideos(pagination.page, searchTerm, statusFilter, field, newOrder);
  };

  const handlePageChange = (page: number) => {
    fetchVideos(page, searchTerm, statusFilter, sortField, sortOrder);
  };

  const resetForm = () => {
    setFormData({ title: "", subtitle: "", status: true, video_file: null });
    if (fileInputRef.current) fileInputRef.current.value = "";
    if (editFileInputRef.current) editFileInputRef.current.value = "";
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.title.trim()) return toast.error("Title is required");
    if (!formData.subtitle.trim()) return toast.error("Subtitle is required");
    if (!formData.video_file) return toast.error("Video file is required");

    try {
      setSubmitting(true);
      const payload = new FormData();
      payload.append("title", formData.title);
      payload.append("subtitle", formData.subtitle);
      payload.append("status", formData.status.toString());
      payload.append("video_file", formData.video_file);

      const response = await fetch("/api/static-videos", {
        method: "POST",
        body: payload,
      });
      const data = await response.json();
      if (data.success) {
        toast.success("Static video created successfully");
        setShowCreateModal(false);
        resetForm();
        fetchVideos(
          pagination.page,
          searchTerm,
          statusFilter,
          sortField,
          sortOrder,
        );
      } else {
        toast.error(data.error || "Failed to create static video");
      }
    } catch (error) {
      console.error("Error creating static video:", error);
      toast.error("Failed to create static video");
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedVideo) return;
    if (!formData.title.trim()) return toast.error("Title is required");
    if (!formData.subtitle.trim()) return toast.error("Subtitle is required");

    try {
      setSubmitting(true);
      const payload = new FormData();
      payload.append("title", formData.title);
      payload.append("subtitle", formData.subtitle);
      payload.append("status", formData.status.toString());
      if (formData.video_file)
        payload.append("video_file", formData.video_file);

      const response = await fetch(`/api/static-videos/${selectedVideo._id}`, {
        method: "PUT",
        body: payload,
      });
      const data = await response.json();
      if (data.success) {
        toast.success("Static video updated successfully");
        setShowEditModal(false);
        resetForm();
        fetchVideos(
          pagination.page,
          searchTerm,
          statusFilter,
          sortField,
          sortOrder,
        );
      } else {
        toast.error(data.error || "Failed to update static video");
      }
    } catch (error) {
      console.error("Error updating static video:", error);
      toast.error("Failed to update static video");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!selectedVideo) return;
    try {
      setSubmitting(true);
      const response = await fetch(`/api/static-videos/${selectedVideo._id}`, {
        method: "DELETE",
      });
      const data = await response.json();
      if (data.success) {
        toast.success("Static video deleted successfully");
        setShowDeleteModal(false);
        setSelectedVideo(null);
        fetchVideos(
          pagination.page,
          searchTerm,
          statusFilter,
          sortField,
          sortOrder,
        );
      } else {
        toast.error(data.error || "Failed to delete static video");
      }
    } catch (error) {
      console.error("Error deleting static video:", error);
      toast.error("Failed to delete static video");
    } finally {
      setSubmitting(false);
    }
  };

  const openEditModal = (video: StaticVideo) => {
    setSelectedVideo(video);
    setFormData({
      title: video.title,
      subtitle: video.subtitle,
      status: video.status,
      video_file: null,
    });
    setShowEditModal(true);
  };

  const openDeleteModal = (video: StaticVideo) => {
    setSelectedVideo(video);
    setShowDeleteModal(true);
  };

  const handleView = (video: StaticVideo) => {
    setViewingVideo(video);
    setIsViewDialogOpen(true);
  };

  const handleCloseModal = () => {
    setShowCreateModal(false);
    setShowEditModal(false);
    resetForm();
  };

  return (
    <div className="p-0">
      <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          {/* <h4 className="text-xl font-semibold text-black dark:text-white">Static Video Management</h4> */}
          {/* <div className="text-sm text-gray-500 mt-1">Total Videos: {pagination.total}</div> */}
        </div>

        <Dialog
          open={showCreateModal || showEditModal}
          onOpenChange={handleCloseModal}
        >
          {/* <Button onClick={() => setShowCreateModal(true)} className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-white hover:bg-opacity-90">
            <Plus className="w-4 h-4 mr-2" /> Add Static Video
          </Button> */}
          <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-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                <DialogHeader className="flex items-center justify-between">
                  <DialogTitle>
                    {showEditModal
                      ? "Edit Static Video"
                      : "Add New Static Video"}
                  </DialogTitle>
                  <X
                    className="h-6 w-6 cursor-pointer p-1 text-white"
                    onClick={handleCloseModal}
                  />
                </DialogHeader>
                <form
                  onSubmit={showCreateModal ? handleCreate : handleEdit}
                  className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2"
                >
                  <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 className="mb-2.5 block font-medium text-black dark:text-white">
                        Title <span className="text-red-600">*</span>
                      </label>
                      <Input
                        type="text"
                        value={formData.title}
                        onChange={(e) =>
                          setFormData({ ...formData, title: e.target.value })
                        }
                        required
                      />
                    </div>
                    <div>
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Subtitle <span className="text-red-600">*</span>
                      </label>
                      <Textarea
                        value={formData.subtitle}
                        onChange={(e) =>
                          setFormData({ ...formData, subtitle: e.target.value })
                        }
                        required
                      />
                    </div>
                    <div>
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Video File <span className="text-red-600">*</span>
                      </label>
                      <input
                        ref={showEditModal ? editFileInputRef : fileInputRef}
                        type="file"
                        accept="video/mp4"
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            video_file: e.target.files?.[0] || null,
                          })
                        }
                        className="dark:border-form-strokedark dark:bg-form-input w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary dark:text-white"
                        required={!showEditModal}
                      />
                      {showEditModal &&
                        selectedVideo &&
                        !formData.video_file && (
                          <div className="mt-2">
                            <video
                              controls
                              className="h-28 w-full rounded-lg border bg-black"
                              src={selectedVideo.video_url}
                            />
                            <p className="mt-1 text-xs text-gray-500">
                              Current uploaded video
                            </p>
                          </div>
                        )}
                    </div>
                    <div>
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Status
                      </label>
                      <select
                        className="dark:border-form-strokedark dark:bg-form-input w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary dark:text-white"
                        value={formData.status ? "true" : "false"}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            status: e.target.value === "true",
                          })
                        }
                      >
                        <option value="true">Active</option>
                        <option value="false">Inactive</option>
                      </select>
                    </div>
                  </div>

                  <div className="flex justify-end gap-3 pb-4 pt-2">
                    <Button
                      type="button"
                      variant="secondary"
                      onClick={handleCloseModal}
                    >
                      Cancel
                    </Button>
                    <Button type="submit" disabled={submitting}>
                      {showCreateModal ? "Create Video" : "Update Video"}
                    </Button>
                  </div>
                </form>
              </div>
            </div>
          </DialogContent>
        </Dialog>

        {/* <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex flex-wrap gap-2">
            <div className="relative">
              <Search className="absolute left-3 top-3 text-gray-400" />
              <Input
                value={searchTerm}
                onChange={e => setSearchTerm(e.target.value)}
                placeholder="Search videos..."
                className="pl-10"
              />
            </div>
            <select className="rounded-lg border-[1.5px] border-stroke bg-transparent px-4 py-3 text-black outline-none dark:border-form-strokedark dark:bg-form-input dark:text-white" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
              <option value="all">All Status</option>
              <option value="true">Active</option>
              <option value="false">Inactive</option>
            </select>
          </div>
        </div> */}
      </div>

      <div className="overflow-auto rounded-lg border border-stroke bg-white shadow-sm dark:border-dark-3 dark:bg-[#0f172a]">
        <Table>
          <TableHeader className="dark:bg-gray-800">
            <TableRow>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("title")}
              >
                Title
              </TableHead>
              <TableHead>Subtitle</TableHead>
              <TableHead>Video</TableHead>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("status")}
              >
                Status
              </TableHead>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("createdAt")}
              >
                Created
              </TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className="dark:bg-gray-800">
            {loading ? (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className="py-8 text-center text-gray-500"
                >
                  Loading...
                </TableCell>
              </TableRow>
            ) : videos.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className="py-8 text-center text-gray-500"
                >
                  No static videos found.
                </TableCell>
              </TableRow>
            ) : (
              videos.map((video) => (
                <TableRow key={video._id}>
                  <TableCell>{video.title}</TableCell>
                  <TableCell>{video.subtitle}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">Uploaded</Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant={video.status ? "default" : "destructive"}>
                      {video.status ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  <TableCell>{formatDate(video.createdAt)}</TableCell>
                  <TableCell className="flex gap-2">
                    <Tooltip text="View">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleView(video)}
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                    </Tooltip>
                    <Tooltip text="Edit">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openEditModal(video)}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                    </Tooltip>
                    <Tooltip text="Delete">
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => openDeleteModal(video)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </Tooltip>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <Dialog
        open={isViewDialogOpen}
        onOpenChange={() => setIsViewDialogOpen(false)}
      >
        <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-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <div className="p-4">
                <div className="mb-4 flex items-center justify-between">
                  <DialogTitle>Video Preview</DialogTitle>
                  <X
                    className="h-6 w-6 cursor-pointer"
                    onClick={() => setIsViewDialogOpen(false)}
                  />
                </div>
                {viewingVideo && (
                  <div className="space-y-4">
                    <div>
                      <h3 className="text-lg font-semibold">
                        {viewingVideo.title}
                      </h3>
                      <p className="text-sm text-gray-500">
                        {viewingVideo.subtitle}
                      </p>
                    </div>
                    <video
                      controls
                      className="w-full rounded-lg border bg-black"
                      src={viewingVideo.video_url}
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog
        open={showDeleteModal}
        onOpenChange={() => setShowDeleteModal(false)}
      >
        <DialogContent className="max-w-md">
          <div className="p-4">
            <DialogHeader>
              <DialogTitle>Delete Static Video</DialogTitle>
            </DialogHeader>
            <p className="text-sm text-gray-600 dark:text-gray-300">
              Are you sure you want to delete this static video? This action
              cannot be undone.
            </p>
            <div className="mt-6 flex justify-end gap-3">
              <Button
                variant="secondary"
                onClick={() => setShowDeleteModal(false)}
              >
                Cancel
              </Button>
              <Button
                variant="destructive"
                onClick={handleDelete}
                disabled={submitting}
              >
                Delete
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default StaticVideoManagement;
