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

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const user = await requireAuthLevel(request, 2);

  const dredgerLocations = await prisma.dredgerLocation.findMany({
    orderBy: { name: 'asc' },
    include: {
      _count: {
        select: { reports: true }
      }
    }
  });

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

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");
  const classType = formData.get("class");

  if (intent === "create") {
    if (typeof name !== "string" || name.length === 0) {
      return json({ errors: { name: "Name is required" } }, { status: 400 });
    }
    // if (typeof classType !== "string" || !["s", "d", "sp"].includes(classType)) {
    //   return json({ errors: { class: "Valid class is required (s, d, or sp)" } }, { status: 400 });
    // }

    try {
      await prisma.dredgerLocation.create({
        data: { name, class: classType }
      });
      return json({ success: "Dredger location created successfully!" });
    } catch (error) {
      return json({ errors: { form: "Dredger location 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 classType !== "string" || !["s", "d", "sp"].includes(classType)) {
      return json({ errors: { class: "Valid class is required (s, d, or sp)" } }, { status: 400 });
    }
    if (typeof id !== "string") {
      return json({ errors: { form: "Invalid dredger location ID" } }, { status: 400 });
    }

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

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

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

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

export default function DredgerLocations() {
  const { user, dredgerLocations } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  const [editingLocation, setEditingLocation] = useState<{ id: number; name: string; class: 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 = editingLocation !== null;

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

  const handleEdit = (location: { id: number; name: string; class: string }) => {
    setEditingLocation(location);
    setShowModal(true);
  };

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

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

  const getClassBadge = (classType: string) => {
    const colors = {
      C: "bg-blue-100 text-blue-800",
      D: "bg-green-100 text-green-800",
      SD: "bg-red-100 text-red-800",
      SP: "bg-purple-100 text-purple-800",
      PC: "bg-yellow-100 text-yellow-800",
      SOPA: "bg-indigo-100 text-indigo-800"

    };
    return colors[classType as keyof typeof colors] || "bg-gray-100 text-gray-800";
  };

  const getClassIcon = (classType: string) => {
    switch (classType) {
      case "C":
      //   return (
      //     <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      //       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
      //     </svg>
      //   );
      // case "D":
      //   return (
      //     <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      //       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 14l-7 7m0 0l-7-7m7 7V3" />
      //     </svg>
      //   );
      // case "SP":
      //   return (
      //     <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      //       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
      //     </svg>
      //   );
      // case "SD":
      //   return (
      //     <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      //       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
      //     </svg>
      //   );

      // case "PC":
      //   return (
      //     <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      //       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
      //     </svg>
      //   );

      // case "SOPA":
      //   return (
      //     <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      //       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
      //     </svg>
      //   );
      default:
        return (
          <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
          </svg>
        );
    }
  };

  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">Dredger Locations Management</h1>
            <p className="mt-1 text-sm text-gray-600">Manage dredger locations with different classes</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 Location
          </button>
        </div>

        {/* Locations 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">
                    Location
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Class
                  </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">
                {dredgerLocations.map((location) => (
                  <tr key={location.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 flex items-center justify-center ${getClassBadge(location.class)}`}>
                            {getClassIcon(location.class)}
                          </div>
                        </div>
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900">{location.name}</div>
                          {/* <div className="text-sm text-gray-500">ID #{location.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 ${getClassBadge(location.class)}`}>
                        {location.class.toUpperCase()} - {location.class === 's' ? 'Standard' : location.class === 'd' ? 'Deep' : 'Special'}
                      </span>
                    </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">
                        {location._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(location)}
                          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={location.id} />
                          <button
                            type="submit"
                            onClick={(e) => {
                              if (!confirm("Are you sure you want to delete this dredger location?")) {
                                e.preventDefault();
                              }
                            }}
                            className="text-red-600 hover:text-red-900 transition-colors duration-150"
                          >
                            Delete
                          </button>
                        </Form>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
          </div>

          {/* Locations Cards - Mobile */}
          <div className="sm:hidden">
            <div className="space-y-4 p-4">
              {dredgerLocations.map((location) => (
                <div key={location.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 flex items-center justify-center ${getClassBadge(location.class)}`}>
                        {getClassIcon(location.class)}
                      </div>
                      <div className="ml-3">
                        <div className="text-sm font-medium text-gray-900">{location.name}</div>
                        <div className="text-xs text-gray-500">{location.class.toUpperCase()}</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">
                      {location._count.reports} reports
                    </span>
                  </div>

                  <div className="mb-3">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getClassBadge(location.class)}`}>
                      {location.class.toUpperCase()} - {location.class === 's' ? 'Standard' : location.class === 'd' ? 'Deep' : 'Special'}
                    </span>
                  </div>

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

          {dredgerLocations.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="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No dredger locations</h3>
              <p className="mt-1 text-sm text-gray-500">Get started by creating your first dredger location.</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 Location
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Form Modal */}
        <FormModal
          isOpen={showModal}
          onClose={handleCloseModal}
          title={isEditing ? "Edit Dredger Location" : "Add New Dredger Location"}
          isSubmitting={isSubmitting}
          submitText={isEditing ? "Update Location" : "Create Location"}
        >
          <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={editingLocation?.id} />}

            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                Location Name
              </label>
              <input
                type="text"
                name="name"
                id="name"
                required
                defaultValue={editingLocation?.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 location name"
              />
              {actionData?.errors?.name && (
                <p className="mt-1 text-sm text-red-600">{actionData.errors.name}</p>
              )}
            </div>

            <div>
              <label htmlFor="class" className="block text-sm font-medium text-gray-700 mb-2">
                Class Type
              </label>
              <select
                name="class"
                id="class"
                required
                defaultValue={editingLocation?.class || ""}
                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"
              >
                <option value="">Select class type</option>
                <option value="C">C - Special</option>
                <option value="D">D - Special</option>
                <option value="SD">SD - Standard</option>
                <option value="SP">SP - Standard</option>
                <option value="PC">PC - Deep</option>
                <option value="SOPA">SOPA - Deep</option>
                {/* <option value="sp">SP - Special</option> */}
              </select>
              {actionData?.errors?.class && (
                <p className="mt-1 text-sm text-red-600">{actionData.errors.class}</p>
              )}
            </div>
          </Form>
        </FormModal>

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