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: "Equipment Management - Phosphat Report" }];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const user = await requireAuthLevel(request, 2);
  
  const equipment = await prisma.equipment.findMany({
    orderBy: [{ category: 'asc' }, { model: 'asc' }]
  });

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

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 category = formData.get("category");
  const model = formData.get("model");
  const number = formData.get("number");

  if (intent === "create") {
    if (typeof category !== "string" || category.length === 0) {
      return json({ errors: { category: "Category is required" } }, { status: 400 });
    }
    if (typeof model !== "string" || model.length === 0) {
      return json({ errors: { model: "Model is required" } }, { status: 400 });
    }
    if (typeof number !== "string" || isNaN(parseInt(number)) || parseInt(number) < 1) {
      return json({ errors: { number: "Valid number is required" } }, { status: 400 });
    }

    try {
      await prisma.equipment.create({
        data: { 
          category, 
          model, 
          number: parseInt(number) 
        }
      });
      return json({ success: "Equipment created successfully!" });
    } catch (error) {
      return json({ errors: { form: "Failed to create equipment" } }, { status: 400 });
    }
  }

  if (intent === "update") {
    if (typeof category !== "string" || category.length === 0) {
      return json({ errors: { category: "Category is required" } }, { status: 400 });
    }
    if (typeof model !== "string" || model.length === 0) {
      return json({ errors: { model: "Model is required" } }, { status: 400 });
    }
    if (typeof number !== "string" || isNaN(parseInt(number)) || parseInt(number) < 1) {
      return json({ errors: { number: "Valid number is required" } }, { status: 400 });
    }
    if (typeof id !== "string") {
      return json({ errors: { form: "Invalid equipment ID" } }, { status: 400 });
    }

    try {
      await prisma.equipment.update({
        where: { id: parseInt(id) },
        data: { 
          category, 
          model, 
          number: parseInt(number) 
        }
      });
      return json({ success: "Equipment updated successfully!" });
    } catch (error) {
      return json({ errors: { form: "Failed to update equipment" } }, { status: 400 });
    }
  }

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

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

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

export default function Equipment() {
  const { user, equipment } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  const [editingEquipment, setEditingEquipment] = useState<{ id: number; category: string; model: string; number: number } | 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 = editingEquipment !== null;

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

  const handleEdit = (item: { id: number; category: string; model: string; number: number }) => {
    setEditingEquipment(item);
    setShowModal(true);
  };

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

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

  const getCategoryBadge = (category: string) => {
    const colors = {
      Dozer: "bg-yellow-100 text-yellow-800",
      Excavator: "bg-blue-100 text-blue-800",
      Loader: "bg-green-100 text-green-800",
      Truck: "bg-red-100 text-red-800"
    };
    return colors[category as keyof typeof colors] || "bg-gray-100 text-gray-800";
  };
  const getCategoryIcon = (category: string) => {
    // Using the same heavy equipment SVG icon with different colors based on category
    const color = {
      "Dozer": "#f59e0b",      // yellow-500
      "Excavator": "#3b82f6",  // blue-500
      "Loader": "#10b981",     // green-500
      "Truck": "#ef4444",      // red-500
    }[category] || "#6b7280";  // gray-500 default
    return (
      <svg className="h-5 w-5" fill="none" stroke={color} viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
      </svg>
    );
  };

  return (
    <DashboardLayout user={user}>
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Equipment Management</h1>
            <p className="mt-1 text-sm text-gray-600">Manage your fleet equipment and machinery</p>
          </div>
          <button
            onClick={handleAdd}
            className="inline-flex items-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 Equipment
          </button>
        </div>

        {/* Equipment Table */}
        <div className="bg-white shadow-sm rounded-lg overflow-hidden">
          <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">
                    Equipment
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Category
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Number
                  </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">
                {equipment.map((item) => (
                  <tr key={item.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 ${getCategoryBadge(item.category)}`}>
                            {getCategoryIcon(item.category)}
                          </div>
                        </div>
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900">{item.model}</div>
                          {/* <div className="text-sm text-gray-500">ID #{item.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 ${getCategoryBadge(item.category)}`}>
                        {item.category}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      <span className="font-mono">{item.number}</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(item)}
                          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={item.id} />
                          <button
                            type="submit"
                            onClick={(e) => {
                              if (!confirm("Are you sure you want to delete this equipment?")) {
                                e.preventDefault();
                              }
                            }}
                            className="text-red-600 hover:text-red-900 transition-colors duration-150"
                          >
                            Delete
                          </button>
                        </Form>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {equipment.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="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No equipment</h3>
              <p className="mt-1 text-sm text-gray-500">Get started by adding your first equipment.</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 Equipment
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Form Modal */}
        <FormModal
          isOpen={showModal}
          onClose={handleCloseModal}
          title={isEditing ? "Edit Equipment" : "Add New Equipment"}
          isSubmitting={isSubmitting}
          submitText={isEditing ? "Update Equipment" : "Create Equipment"}
        >
          <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={editingEquipment?.id} />}
            
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div>
                <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-2">
                  Category
                </label>
                <select
                  name="category"
                  id="category"
                  required
                  defaultValue={editingEquipment?.category || ""}
                  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 category</option>
                  <option value="Dozer">Dozer</option>
                  <option value="Excavator">Excavator</option>
                  <option value="Loader">Loader</option>
                  <option value="Truck">Truck</option>
                </select>
                {actionData?.errors?.category && (
                  <p className="mt-1 text-sm text-red-600">{actionData.errors.category}</p>
                )}
              </div>
              
              <div>
                <label htmlFor="number" className="block text-sm font-medium text-gray-700 mb-2">
                  Number
                </label>
                <input
                  type="number"
                  name="number"
                  id="number"
                  min="1"
                  required
                  defaultValue={editingEquipment?.number || ""}
                  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 number"
                />
                {actionData?.errors?.number && (
                  <p className="mt-1 text-sm text-red-600">{actionData.errors.number}</p>
                )}
              </div>
            </div>

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

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