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: "Areas Management - Alhaffer Reporting System" }];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const user = await requireAuthLevel(request, 2);
  
  const areas = await prisma.area.findMany({
    orderBy: { name: 'asc' },
    include: {
      _count: {
        select: { reports: true }
      }
    }
  });

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

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.area.create({
        data: { name }
      });
      return json({ success: "Area created successfully!" });
    } catch (error) {
      return json({ errors: { form: "Area name already exists" } }, { 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 area ID" } }, { status: 400 });
    }

    try {
      await prisma.area.update({
        where: { id: parseInt(id) },
        data: { name }
      });
      return json({ success: "Area updated successfully!" });
    } catch (error) {
      return json({ errors: { form: "Area name already exists" } }, { status: 400 });
    }
  }

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

    try {
      await prisma.area.delete({
        where: { id: parseInt(id) }
      });
      return json({ success: "Area deleted successfully!" });
    } catch (error) {
      return json({ errors: { form: "Cannot delete area with existing reports" } }, { status: 400 });
    }
  }

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

export default function Areas() {
  const { user, areas } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  const [editingArea, setEditingArea] = 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 = editingArea !== null;

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

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

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

  const handleCloseModal = () => {
    setShowModal(false);
    setEditingArea(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">Areas Management</h1>
            <p className="mt-1 text-sm text-gray-600">Manage operational areas for your reports</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 Area
          </button>
        </div>

        {/* Areas 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">
                    Area Name
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Reports Count
                  </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">
                {areas.map((area, index) => (
                  <tr key={area.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-100 flex items-center justify-center">
                            <svg className="h-5 w-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                          </div>
                        </div>
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900">{area.name}</div>
                          {/* <div className="text-sm text-gray-500">Area #{area.id}</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-blue-100 text-blue-800">
                        {area._count.reports} reports
                      </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(area)}
                          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={area.id} />
                          <button
                            type="submit"
                            onClick={(e) => {
                              if (!confirm("Are you sure you want to delete this area?")) {
                                e.preventDefault();
                              }
                            }}
                            className="text-red-600 hover:text-red-900 transition-colors duration-150"
                          >
                            Delete
                          </button>
                        </Form>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
          </div>

          {/* Areas Cards - Mobile */}
          <div className="sm:hidden">
            <div className="space-y-4 p-4">
              {areas.map((area) => (
                <div key={area.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-100 flex items-center justify-center">
                        <svg className="h-5 w-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                      </div>
                      <div className="ml-3">
                        <div className="text-sm font-medium text-gray-900">{area.name}</div>
                      </div>
                    </div>
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {area._count.reports} reports
                    </span>
                  </div>

                  <div className="flex flex-col space-y-2">
                    <button
                      onClick={() => handleEdit(area)}
                      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 Area
                    </button>
                    <Form method="post" className="w-full">
                      <input type="hidden" name="intent" value="delete" />
                      <input type="hidden" name="id" value={area.id} />
                      <button
                        type="submit"
                        onClick={(e) => {
                          if (!confirm("Are you sure you want to delete this area?")) {
                            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 Area
                      </button>
                    </Form>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {areas.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="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No areas</h3>
              <p className="mt-1 text-sm text-gray-500">Get started by creating your first area.</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 Area
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Form Modal */}
        <FormModal
          isOpen={showModal}
          onClose={handleCloseModal}
          title={isEditing ? "Edit Area" : "Add New Area"}
          isSubmitting={isSubmitting}
          submitText={isEditing ? "Update Area" : "Create Area"}
        >
          <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={editingArea?.id} />}
            
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                Area Name
              </label>
              <input
                type="text"
                name="name"
                id="name"
                required
                defaultValue={editingArea?.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 area 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>
  );
}