import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation } from "@remix-run/react";
import { requireAuthLevel } from "~/utils/auth.server";
import DashboardLayout from "~/components/DashboardLayout";
import FormModal from "~/components/FormModal";
import Toast from "~/components/Toast";
import { useState, useEffect } from "react";
import { prisma } from "~/utils/db.server";

export const meta: MetaFunction = () => [{ title: "Foreman Management - Alhaffer Reporting System" }];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const user = await requireAuthLevel(request, 2);
  
  const foremen = await prisma.foreman.findMany({
    orderBy: { name: 'asc' }
  });

  return json({ user, foremen });
};

export const action = async ({ request }: ActionFunctionArgs) => {
  await requireAuthLevel(request, 2);
  
  const formData = await request.formData();
  const intent = formData.get("intent");
  const id = formData.get("id");
  const name = formData.get("name");

  if (intent === "create") {
    if (typeof name !== "string" || name.length === 0) {
      return json({ errors: { name: "Name is required" } }, { status: 400 });
    }

    try {
      await prisma.foreman.create({
        data: { name }
      });
      return json({ success: "Foreman created successfully!" });
    } catch (error) {
      return json({ errors: { form: "Failed to create foreman" } }, { status: 400 });
    }
  }

  if (intent === "update") {
    if (typeof name !== "string" || name.length === 0) {
      return json({ errors: { name: "Name is required" } }, { status: 400 });
    }
    if (typeof id !== "string") {
      return json({ errors: { form: "Invalid foreman ID" } }, { status: 400 });
    }

    try {
      await prisma.foreman.update({
        where: { id: parseInt(id) },
        data: { name }
      });
      return json({ success: "Foreman updated successfully!" });
    } catch (error) {
      return json({ errors: { form: "Failed to update foreman" } }, { status: 400 });
    }
  }

  if (intent === "delete") {
    if (typeof id !== "string") {
      return json({ errors: { form: "Invalid foreman ID" } }, { status: 400 });
    }

    try {
      await prisma.foreman.delete({
        where: { id: parseInt(id) }
      });
      return json({ success: "Foreman deleted successfully!" });
    } catch (error) {
      return json({ errors: { form: "Failed to delete foreman" } }, { status: 400 });
    }
  }

  return json({ errors: { form: "Invalid action" } }, { status: 400 });
};

export default function Foreman() {
  const { user, foremen } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  const [editingForeman, setEditingForeman] = useState<{ id: number; name: string } | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);

  const isSubmitting = navigation.state === "submitting";
  const isEditing = editingForeman !== null;

  // Handle success/error messages
  useEffect(() => {
    if (actionData?.success) {
      setToast({ message: actionData.success, type: "success" });
      setShowModal(false);
      setEditingForeman(null);
    } else if (actionData?.errors?.form) {
      setToast({ message: actionData.errors.form, type: "error" });
    }
  }, [actionData]);

  const handleEdit = (foreman: { id: number; name: string }) => {
    setEditingForeman(foreman);
    setShowModal(true);
  };

  const handleAdd = () => {
    setEditingForeman(null);
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setEditingForeman(null);
  };

  return (
    <DashboardLayout user={user}>
      <div className="space-y-6">
        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center space-y-4 sm:space-y-0">
          <div>
            <h1 className="text-xl sm:text-2xl font-bold text-gray-900">Foreman Management</h1>
            <p className="mt-1 text-sm text-gray-600">Manage site foremen and supervisors</p>
          </div>
          <button
            onClick={handleAdd}
            className="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200"
          >
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Add New Foreman
          </button>
        </div>

        {/* Foremen Table - Desktop */}
        <div className="bg-white shadow-sm rounded-lg overflow-hidden">
          <div className="hidden sm:block">
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Foreman
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    ID
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {foremen.map((foreman) => (
                  <tr key={foreman.id} className="hover:bg-gray-50 transition-colors duration-150">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <div className="flex-shrink-0 h-10 w-10">
                          <div className="h-10 w-10 rounded-full bg-indigo-500 flex items-center justify-center">
                            <span className="text-sm font-medium text-white">
                              {foreman.name.charAt(0).toUpperCase()}
                            </span>
                          </div>
                        </div>
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900">{foreman.name}</div>
                          {/* <div className="text-sm text-gray-500">Site Foreman</div> */}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                        #{foreman.id}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex justify-end space-x-2">
                        <button
                          onClick={() => handleEdit(foreman)}
                          className="text-indigo-600 hover:text-indigo-900 transition-colors duration-150"
                        >
                          Edit
                        </button>
                        <Form method="post" className="inline">
                          <input type="hidden" name="intent" value="delete" />
                          <input type="hidden" name="id" value={foreman.id} />
                          <button
                            type="submit"
                            onClick={(e) => {
                              if (!confirm("Are you sure you want to delete this foreman?")) {
                                e.preventDefault();
                              }
                            }}
                            className="text-red-600 hover:text-red-900 transition-colors duration-150"
                          >
                            Delete
                          </button>
                        </Form>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
          </div>

          {/* Foremen Cards - Mobile */}
          <div className="sm:hidden">
            <div className="space-y-4 p-4">
              {foremen.map((foreman) => (
                <div key={foreman.id} className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center">
                      <div className="h-10 w-10 rounded-full bg-indigo-500 flex items-center justify-center">
                        <span className="text-sm font-medium text-white">
                          {foreman.name.charAt(0).toUpperCase()}
                        </span>
                      </div>
                      <div className="ml-3">
                        <div className="text-sm font-medium text-gray-900">{foreman.name}</div>
                        <div className="text-xs text-gray-500">Site Foreman</div>
                      </div>
                    </div>
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                      #{foreman.id}
                    </span>
                  </div>

                  <div className="flex flex-col space-y-2">
                    <button
                      onClick={() => handleEdit(foreman)}
                      className="w-full text-center px-3 py-2 text-sm text-indigo-600 bg-indigo-50 rounded-md hover:bg-indigo-100 transition-colors duration-150"
                    >
                      Edit Foreman
                    </button>
                    <Form method="post" className="w-full">
                      <input type="hidden" name="intent" value="delete" />
                      <input type="hidden" name="id" value={foreman.id} />
                      <button
                        type="submit"
                        onClick={(e) => {
                          if (!confirm("Are you sure you want to delete this foreman?")) {
                            e.preventDefault();
                          }
                        }}
                        className="w-full text-center px-3 py-2 text-sm text-red-600 bg-red-50 rounded-md hover:bg-red-100 transition-colors duration-150"
                      >
                        Delete Foreman
                      </button>
                    </Form>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {foremen.length === 0 && (
            <div className="text-center py-12">
              <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No foremen</h3>
              <p className="mt-1 text-sm text-gray-500">Get started by adding your first foreman.</p>
              <div className="mt-6">
                <button
                  onClick={handleAdd}
                  className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
                >
                  <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                  </svg>
                  Add Foreman
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Form Modal */}
        <FormModal
          isOpen={showModal}
          onClose={handleCloseModal}
          title={isEditing ? "Edit Foreman" : "Add New Foreman"}
          isSubmitting={isSubmitting}
          submitText={isEditing ? "Update Foreman" : "Create Foreman"}
        >
          <Form method="post" id="modal-form" className="space-y-4">
            <input type="hidden" name="intent" value={isEditing ? "update" : "create"} />
            {isEditing && <input type="hidden" name="id" value={editingForeman?.id} />}
            
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                Foreman Name
              </label>
              <input
                type="text"
                name="name"
                id="name"
                required
                defaultValue={editingForeman?.name || ""}
                className="block w-full border-gray-300 h-9 p-2 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder="Enter foreman's full name"
              />
              {actionData?.errors?.name && (
                <p className="mt-1 text-sm text-red-600">{actionData.errors.name}</p>
              )}
            </div>
          </Form>
        </FormModal>

        {/* Toast Notifications */}
        {toast && (
          <Toast
            message={toast.message}
            type={toast.type}
            onClose={() => setToast(null)}
          />
        )}
      </div>
    </DashboardLayout>
  );
}