"use client";

import { useState, useEffect } from "react";
import { X, AlertCircle, CheckCircle, ChevronDown } from "lucide-react";
import logger from "@/lib/logger";
import type { VoiceActionType } from "@/lib/types/voice-agent-staff.types";

interface StaffMember {
  id: string;
  name: string;
}

interface CreateActionModalProps {
  conversationId: string;
  staffMembers: StaffMember[];
  isOpen: boolean;
  onClose: () => void;
  onCreated: () => void;
}

const actionTypes: {
  value: VoiceActionType;
  label: string;
  description: string;
}[] = [
  {
    value: "CALL_BACK",
    label: "Call Back",
    description: "Schedule a follow-up call with the customer",
  },
  {
    value: "SEND_EMAIL",
    label: "Send Email",
    description: "Send an email to the customer",
  },
  {
    value: "BOOK_APPOINTMENT",
    label: "Book Appointment",
    description: "Book an appointment for the customer",
  },
  {
    value: "ESCALATE",
    label: "Escalate",
    description: "Escalate to a supervisor or specialist",
  },
  {
    value: "CUSTOM",
    label: "Custom",
    description: "Custom action with specific instructions",
  },
];

export default function CreateActionModal({
  conversationId,
  staffMembers,
  isOpen,
  onClose,
  onCreated,
}: CreateActionModalProps) {
  // Form state
  const [type, setType] = useState<VoiceActionType>("CALL_BACK");
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [dueAt, setDueAt] = useState("");
  const [assignedTo, setAssignedTo] = useState("");

  // UI state
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Reset form when modal opens
  useEffect(() => {
    if (isOpen) {
      setType("CALL_BACK");
      setTitle("");
      setDescription("");
      setDueAt("");
      setAssignedTo("");
      setError(null);
      setSuccess(false);
    }
  }, [isOpen]);

  // Close on Escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape" && !submitting) onClose();
    };
    if (isOpen) {
      window.addEventListener("keydown", handleEscape);
      return () => window.removeEventListener("keydown", handleEscape);
    }
  }, [isOpen, onClose, submitting]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = "";
      };
    }
  }, [isOpen]);

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

    // Validate
    if (!title.trim()) {
      setError("Title is required");
      return;
    }

    try {
      setSubmitting(true);

      const payload: Record<string, unknown> = {
        conversationId,
        type,
        title: title.trim(),
      };

      if (description.trim()) {
        payload.description = description.trim();
      }

      if (dueAt) {
        payload.dueAt = new Date(dueAt).toISOString();
      }

      if (assignedTo) {
        payload.assignedTo = assignedTo;
      }

      const response = await fetch("/api/staff/voice-agents/actions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to create action");
      }

      setSuccess(true);

      // Close modal after a short delay
      setTimeout(() => {
        onCreated();
        onClose();
      }, 1000);
    } catch (err) {
      logger.error("Failed to create action", { error: err, conversationId });
      setError(err instanceof Error ? err.message : "Failed to create action");
    } finally {
      setSubmitting(false);
    }
  };

  // Get minimum date for due date picker (today)
  const minDate = new Date().toISOString().split("T")[0];

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200">
          <h3 className="text-lg font-bold text-gray-900">Create Action</h3>
          <button
            onClick={onClose}
            disabled={submitting}
            className="p-2 rounded-lg hover:bg-gray-100 transition disabled:opacity-50"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* Success State */}
        {success ? (
          <div className="p-8 text-center">
            <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-8 h-8 text-green-600" />
            </div>
            <h4 className="text-lg font-semibold text-gray-900 mb-2">
              Action Created!
            </h4>
            <p className="text-gray-600">
              The action has been added successfully.
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            <div className="p-4 space-y-4">
              {/* Error Message */}
              {error && (
                <div className="p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2 text-red-700">
                  <AlertCircle className="w-4 h-4 flex-shrink-0" />
                  <span className="text-sm">{error}</span>
                </div>
              )}

              {/* Type */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Action Type <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <select
                    value={type}
                    onChange={(e) => setType(e.target.value as VoiceActionType)}
                    disabled={submitting}
                    className="appearance-none w-full pl-4 pr-10 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white disabled:bg-gray-100"
                  >
                    {actionTypes.map((actionType) => (
                      <option key={actionType.value} value={actionType.value}>
                        {actionType.label}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  {actionTypes.find((t) => t.value === type)?.description}
                </p>
              </div>

              {/* Title */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Title <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  disabled={submitting}
                  placeholder="e.g., Follow up about appointment inquiry"
                  className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100"
                  maxLength={200}
                />
              </div>

              {/* Description */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Description <span className="text-gray-400">(optional)</span>
                </label>
                <textarea
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  disabled={submitting}
                  placeholder="Add any additional details or context..."
                  rows={3}
                  className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none disabled:bg-gray-100"
                  maxLength={1000}
                />
              </div>

              {/* Due Date */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Due Date <span className="text-gray-400">(optional)</span>
                </label>
                <input
                  type="date"
                  value={dueAt}
                  onChange={(e) => setDueAt(e.target.value)}
                  disabled={submitting}
                  min={minDate}
                  className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100"
                />
              </div>

              {/* Assign To */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Assign To <span className="text-gray-400">(optional)</span>
                </label>
                <div className="relative">
                  <select
                    value={assignedTo}
                    onChange={(e) => setAssignedTo(e.target.value)}
                    disabled={submitting}
                    className="appearance-none w-full pl-4 pr-10 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white disabled:bg-gray-100"
                  >
                    <option value="">Unassigned</option>
                    {staffMembers.map((staff) => (
                      <option key={staff.id} value={staff.id}>
                        {staff.name}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-gray-200 flex gap-3">
              <button
                type="button"
                onClick={onClose}
                disabled={submitting}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition disabled:opacity-50"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={submitting || !title.trim()}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {submitting ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
                    Creating...
                  </>
                ) : (
                  "Create Action"
                )}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
