"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useReplyToSupportTicket } from "@/hooks/use-support-tickets";
import {
  SupportTicket,
  SupportTicketStatus,
  SupportTicketType,
} from "@/types/api";
import {
  Loader2,
  Send,
  User,
  Mail,
  Calendar,
  Tag,
  AlertCircle,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";

interface SupportTicketReplyDialogProps {
  ticket: SupportTicket | null;
  isOpen: boolean;
  onClose: () => void;
}

export function SupportTicketReplyDialog({
  ticket,
  isOpen,
  onClose,
}: SupportTicketReplyDialogProps) {
  const [response, setResponse] = useState("");
  const [subject, setSubject] = useState("");
  const [status, setStatus] = useState<SupportTicketStatus>(
    SupportTicketStatus.open
  );
  const [userStatusUpdates, setUserStatusUpdates] = useState({
    isDisabled: ticket?.user?.isDisabled || false,
    isLocked: ticket?.user?.isLocked || false,
    isDeleted: ticket?.user?.isDeleted || false,
  });

  const replyMutation = useReplyToSupportTicket();

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

    if (!ticket || !response.trim() || !subject.trim()) {
      return;
    }

    try {
      await replyMutation.mutateAsync({
        ticketId: ticket._id,
        replyData: {
          response: response.trim(),
          subject: subject.trim(),
          status,
          userStatusUpdates: Object.keys(userStatusUpdates).some(
            (key) => userStatusUpdates[key as keyof typeof userStatusUpdates]
          )
            ? userStatusUpdates
            : undefined,
        },
      });

      // Reset form
      setResponse("");
      setSubject("");
      setStatus(SupportTicketStatus.open);
      setUserStatusUpdates({
        isDisabled: ticket?.user?.isDisabled || false,
        isLocked: ticket?.user?.isLocked || false,
        isDeleted: ticket?.user?.isDeleted || false,
      });

      onClose();
    } catch (error) {
      console.error("Error sending reply:", error);
    }
  };

  const handleClose = () => {
    if (!replyMutation.isPending) {
      setResponse("");
      setSubject("");
      setStatus(SupportTicketStatus.open);
      setUserStatusUpdates({
        isDisabled: ticket?.user?.isDisabled || false,
        isLocked: ticket?.user?.isLocked || false,
        isDeleted: ticket?.user?.isDeleted || false,
      });
      onClose();
    }
  };

  const getStatusColor = (status: SupportTicketStatus) => {
    switch (status) {
      case "open":
        return "bg-red-100 text-red-800";
      case "in_progress":
        return "bg-yellow-100 text-yellow-800";
      case "closed":
        return "bg-green-100 text-green-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  const getTypeColor = (type: SupportTicketType) => {
    switch (type) {
      case "bug":
        return "bg-red-100 text-red-800";
      case "account_recovery":
        return "bg-orange-100 text-orange-800";
      case "other":
        return "bg-blue-100 text-blue-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  if (!ticket) return null;

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Send className="h-5 w-5" />
            Reply to Support Ticket
          </DialogTitle>
          <DialogDescription>
            Send a response to the user and optionally update their account
            status.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* Ticket Information */}
          <div className=" p-4 rounded-lg space-y-4">
            <h3 className="font-semibold text-lg">Ticket Information</h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <User className="h-4 w-4 " />
                  <span className="font-medium">User:</span>
                  <span>{ticket.user.fullName}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4 " />
                  <span className="font-medium">Email:</span>
                  <span className="text-sm">{ticket.user.email}</span>
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4 " />
                  <span className="font-medium">Created:</span>
                  <span className="text-sm">
                    {new Date(ticket.createdAt).toLocaleDateString()}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <Tag className="h-4 w-4 " />
                  <span className="font-medium">Type:</span>
                  <Badge className={getTypeColor(ticket.type)}>
                    {ticket.type.replace("_", " ").toUpperCase()}
                  </Badge>
                </div>
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <span className="font-medium">Status:</span>
                <Badge className={getStatusColor(ticket.status)}>
                  {ticket.status.replace("_", " ").toUpperCase()}
                </Badge>
              </div>
              <div>
                <span className="font-medium">Subject:</span>
                <p className="text-sm  mt-1">{ticket.subject}</p>
              </div>
              <div>
                <span className="font-medium">Description:</span>
                <p className="text-sm  mt-1 whitespace-pre-wrap">
                  {ticket.description}
                </p>
              </div>
            </div>
          </div>

          {/* Reply Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="subject">Email Subject *</Label>
              <Input
                id="subject"
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                placeholder="Enter email subject"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="response">Response Message *</Label>
              <Textarea
                id="response"
                value={response}
                onChange={(e) => setResponse(e.target.value)}
                placeholder="Enter your response to the user"
                rows={6}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="status">Update Ticket Status</Label>
              <Select
                value={status}
                onValueChange={(value: SupportTicketStatus) => setStatus(value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="open">Open</SelectItem>
                  <SelectItem value="in_progress">In Progress</SelectItem>
                  <SelectItem value="closed">Closed</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* User Status Updates */}
            {/* <div className="space-y-4 p-4  border border-orange-200 rounded-lg">
              <div className="flex items-center gap-2">
                <AlertCircle className="h-5 w-5 text-orange-600" />
                <h4 className="font-semibold text-orange-800">
                  Account Recovery Options
                </h4>
              </div>
              <p className="text-sm text-orange-700">
                This is an account recovery ticket. You can restore the
                user&apos;s account and all related data.
              </p>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label htmlFor="restore-account" className="text-black">
                      {userStatusUpdates.isDeleted
                        ? "Restore Deleted Account"
                        : "Delete Account"}
                    </Label>
                    <p className="text-sm text-gray-600">
                      {userStatusUpdates.isDeleted
                        ? "Account is currently deleted - toggle to restore the user's account and all related data"
                        : "Account is currently active - toggle to delete the user's account"}
                    </p>
                  </div>
                  <Switch
                    id="restore-account"
                    checked={userStatusUpdates.isDeleted}
                    onCheckedChange={(checked) =>
                      setUserStatusUpdates((prev) => ({
                        ...prev,
                        isDeleted: checked,
                      }))
                    }
                  />
                </div>
              </div>
            </div>

            <div className="space-y-4 p-4  border rounded-lg">
              <h4 className="font-semibold">
                User Account Status Updates (Optional)
              </h4>
              <p className="text-sm text-gray-600">
                These changes will be applied to the user&apos;s account when
                the reply is sent. Current status is shown below.
              </p>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label htmlFor="disable-account">
                      {userStatusUpdates.isDisabled
                        ? "Enable Account"
                        : "Disable Account"}
                    </Label>
                    <p className="text-sm text-gray-600">
                      {userStatusUpdates.isDisabled
                        ? "Currently disabled - toggle to enable the user's account"
                        : "Currently enabled - toggle to temporarily disable the user's account"}
                    </p>
                  </div>
                  <Switch
                    id="disable-account"
                    checked={userStatusUpdates.isDisabled}
                    onCheckedChange={(checked) =>
                      setUserStatusUpdates((prev) => ({
                        ...prev,
                        isDisabled: checked,
                      }))
                    }
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label htmlFor="lock-account">
                      {userStatusUpdates.isLocked
                        ? "Unlock Account"
                        : "Lock Account"}
                    </Label>
                    <p className="text-sm text-gray-600">
                      {userStatusUpdates.isLocked
                        ? "Currently locked - toggle to unlock the user's account"
                        : "Currently unlocked - toggle to lock the user's account to prevent login"}
                    </p>
                  </div>
                  <Switch
                    id="lock-account"
                    checked={userStatusUpdates.isLocked}
                    onCheckedChange={(checked) =>
                      setUserStatusUpdates((prev) => ({
                        ...prev,
                        isLocked: checked,
                      }))
                    }
                  />
                </div>
              </div>
            </div> */}
          </form>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={handleClose}
            disabled={replyMutation.isPending}
          >
            Cancel
          </Button>
          <Button
            type="submit"
            onClick={handleSubmit}
            disabled={
              replyMutation.isPending || !response.trim() || !subject.trim()
            }
          >
            {replyMutation.isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Sending...
              </>
            ) : (
              <>
                <Send className="mr-2 h-4 w-4" />
                Send Reply
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
