"use client";
import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { IconX, SettingsIcon } from "@/components/icons";
import { useRouter, usePathname } from "next/navigation";

interface WorkflowSetupModalProps {
  isOpen: boolean;
  onClose: () => void;
  workflowInfo?: {
    hasWorkflowSetup: boolean;
    defaultWorkflowId?: number;
    defaultWorkflowName?: string;
    requiresApproval?: boolean;
    autoPublishArticles?: boolean;
    isApprovalActive?: boolean;
  };
  onRefresh?: () => Promise<void>;
}

export default function WorkflowSetupModal({
  isOpen,
  onClose,
  workflowInfo,
  onRefresh,
}: WorkflowSetupModalProps) {
  const router = useRouter();
  const pathname = usePathname();
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setIsVisible(true);
    }
  }, [isOpen]);

  const handleClose = () => {
    // Allow closing if workflow is setup OR if user is on tenant settings page
    if (
      workflowInfo?.hasWorkflowSetup ||
      pathname?.includes("/admin/settings/tenant") ||
      pathname?.includes("/tenant")
    ) {
      setIsVisible(false);
      setTimeout(() => {
        onClose();
      }, 200);
    }
  };

  const handleSetupWorkflow = () => {
    // Navigate to tenant settings
    router.push("/admin/settings/tenant");
    // Modal will be auto-hidden by WorkflowModalProvider when user reaches tenant settings page
  };

  if (!isOpen) return null;

  return (
    <Dialog
      open={isVisible}
      onOpenChange={
        workflowInfo?.hasWorkflowSetup ||
        pathname?.includes("/admin/settings/tenant") ||
        pathname?.includes("/tenant")
          ? handleClose
          : undefined
      }
    >
      <DialogContent
        className="max-w-md"
        onPointerDownOutside={(e) => {
          // Prevent closing by clicking outside unless workflow is setup or on tenant settings page
          if (
            !workflowInfo?.hasWorkflowSetup &&
            !pathname?.includes("/admin/settings/tenant") &&
            !pathname?.includes("/tenant")
          ) {
            e.preventDefault();
          }
        }}
        onEscapeKeyDown={(e) => {
          // Prevent closing by pressing ESC unless workflow is setup or on tenant settings page
          if (
            !workflowInfo?.hasWorkflowSetup &&
            !pathname?.includes("/admin/settings/tenant") &&
            !pathname?.includes("/tenant")
          ) {
            e.preventDefault();
          }
        }}
      >
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            {workflowInfo?.hasWorkflowSetup ? (
              <div className="h-5 w-5 rounded-full bg-green-600 flex items-center justify-center">
                <span className="text-white text-xs">✓</span>
              </div>
            ) : (
              <div className="h-5 w-5 rounded-full bg-orange-600 flex items-center justify-center">
                <span className="text-white text-xs">!</span>
              </div>
            )}
            Workflow Status
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {
            !workflowInfo?.hasWorkflowSetup ? (
              // No Workflow Setup
              <Card className="border-orange-200 bg-orange-50">
                <CardContent className="p-4">
                  <div className="flex items-start gap-3">
                    <div className="h-6 w-6 rounded-full bg-orange-600 flex items-center justify-center mt-1">
                      <span className="text-white text-sm">!</span>
                    </div>
                    <div className="flex-1">
                      <h3 className="font-medium text-orange-900 mb-2">
                        Workflow Belum Dikonfigurasi
                      </h3>
                      <p className="text-sm text-orange-700 mb-4">
                        Anda belum melakukan setup workflow, silahkan setup
                        terlebih dahulu.
                      </p>
                      <div className="flex gap-2">
                        <Button
                          onClick={handleSetupWorkflow}
                          className="bg-orange-600 hover:bg-orange-700 text-white"
                          size="sm"
                        >
                          <SettingsIcon className="h-4 w-4 mr-2" />
                          Setup Workflow
                        </Button>
                        {(pathname?.includes("/admin/settings/tenant") ||
                          pathname?.includes("/tenant")) && (
                          <Button
                            variant="outline"
                            onClick={handleClose}
                            size="sm"
                          >
                            Cancel
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ) : (
              <Card className="border-green-200 bg-green-50">
                <CardContent className="p-5 space-y-4">
                  <div className="flex items-start gap-3">
                    <div className="h-6 w-6 rounded-full bg-green-600 flex items-center justify-center mt-1">
                      <span className="text-white text-sm">✓</span>
                    </div>
                    <div className="flex-1">
                      <h3 className="font-semibold text-green-900 mb-3">
                        Workflow Sudah Dikonfigurasi
                      </h3>

                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-gray-600">
                            Default Workflow
                          </span>
                          <span className="font-medium">
                            {workflowInfo.defaultWorkflowName}
                          </span>
                        </div>

                        <div className="flex justify-between">
                          <span className="text-gray-600">Workflow ID</span>
                          <span className="font-mono">
                            #{workflowInfo.defaultWorkflowId}
                          </span>
                        </div>

                        <div className="flex justify-between">
                          <span className="text-gray-600">
                            Requires Approval
                          </span>
                          <span
                            className={
                              workflowInfo.requiresApproval
                                ? "text-green-600 font-medium"
                                : "text-gray-500"
                            }
                          >
                            {workflowInfo.requiresApproval ? "Yes" : "No"}
                          </span>
                        </div>

                        <div className="flex justify-between">
                          <span className="text-gray-600">Auto Publish</span>
                          <span
                            className={
                              workflowInfo.autoPublishArticles
                                ? "text-green-600 font-medium"
                                : "text-gray-500"
                            }
                          >
                            {workflowInfo.autoPublishArticles ? "Yes" : "No"}
                          </span>
                        </div>

                        <div className="flex justify-between">
                          <span className="text-gray-600">Approval Status</span>
                          <span
                            className={
                              workflowInfo.isApprovalActive
                                ? "text-green-600 font-medium"
                                : "text-red-600 font-medium"
                            }
                          >
                            {workflowInfo.isApprovalActive
                              ? "Active"
                              : "Inactive"}
                          </span>
                        </div>
                      </div>

                      {/* <div className="flex gap-2 mt-4">
                      <Button
                        onClick={handleSetupWorkflow}
                        variant="outline"
                        size="sm"
                      >
                        <SettingsIcon className="h-4 w-4 mr-2" />
                        Manage Workflow
                      </Button>

                      <Button variant="outline" onClick={handleClose} size="sm">
                        Close
                      </Button>
                    </div> */}
                    </div>
                  </div>
                </CardContent>
              </Card>
               // Workflow Setup Complete
            // <Card className="border-green-200 bg-green-50">
            //   <CardContent className="p-4">
            //     <div className="flex items-start gap-3">
            //       <div className="h-6 w-6 rounded-full bg-green-600 flex items-center justify-center mt-1">
            //         <span className="text-white text-sm">✓</span>
            //       </div>
            //       <div className="flex-1">
            //         <h3 className="font-medium text-green-900 mb-2">
            //           Workflow Sudah Dikonfigurasi
            //         </h3>
            //         <div className="space-y-2 text-sm text-green-700">
            //           <div className="flex items-center justify-between">
            //             <span>Workflow:</span>
            //             <span className="font-medium">{workflowInfo.defaultWorkflowName}</span>
            //           </div>
            //           <div className="flex items-center justify-between">
            //             <span>Requires Approval:</span>
            //             <span className={`font-medium ${workflowInfo.requiresApproval ? 'text-green-600' : 'text-gray-500'}`}>
            //               {workflowInfo.requiresApproval ? 'Yes' : 'No'}
            //             </span>
            //           </div>
            //           <div className="flex items-center justify-between">
            //             <span>Auto Publish:</span>
            //             <span className={`font-medium ${workflowInfo.autoPublishArticles ? 'text-green-600' : 'text-gray-500'}`}>
            //               {workflowInfo.autoPublishArticles ? 'Yes' : 'No'}
            //             </span>
            //           </div>
            //           <div className="flex items-center justify-between">
            //             <span>Status:</span>
            //             <span className={`font-medium ${workflowInfo.isApprovalActive ? 'text-green-600' : 'text-gray-500'}`}>
            //               {workflowInfo.isApprovalActive ? 'Active' : 'Inactive'}
            //             </span>
            //           </div>
            //         </div>
            //         <div className="flex gap-2 mt-4">
            //           <Button
            //             onClick={handleSetupWorkflow}
            //             variant="outline"
            //             size="sm"
            //           >
            //             <SettingsIcon className="h-4 w-4 mr-2" />
            //             Manage Workflow
            //           </Button>
            //         </div>
            //       </div>
            //     </div>
            //   </CardContent>
            // </Card>
            )
           
          }
        </div>
      </DialogContent>
    </Dialog>
  );
}
