"use client";

import { useState, useEffect } from "react";
import {
  getStatesAction,
  createStateAction,
  updateStateAction,
  deleteStateAction,
  type State,
  type StateRequest,
  type LengthAwarePaginator,
} from "@/features/locations";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

export default function TestStatesPage() {
  const [states, setStates] = useState<LengthAwarePaginator<State> | null>(
    null
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);

  // Form state
  const [formData, setFormData] = useState<StateRequest>({
    name: "",
    status: "active",
  });
  const [editingId, setEditingId] = useState<number | null>(null);

  // Load states
  const loadStates = async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await getStatesAction(search || undefined, page);
      if (result.success && result.data) {
        setStates(result.data);
      } else {
        setError(result.error || "Failed to load states");
      }
    } catch {
      setError("An error occurred");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadStates();
  }, [page]);

  // Create or update state
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const result = editingId
        ? await updateStateAction(editingId, formData)
        : await createStateAction(formData);

      if (result.success) {
        setFormData({ name: "", status: "active" });
        setEditingId(null);
        await loadStates();
      } else {
        setError(result.error || "Operation failed");
      }
    } catch {
      setError("An error occurred");
    } finally {
      setLoading(false);
    }
  };

  // Delete state
  const handleDelete = async (id: number) => {
    if (!confirm("Are you sure you want to delete this state?")) return;

    setLoading(true);
    setError(null);

    try {
      const result = await deleteStateAction(id);
      if (result.success) {
        await loadStates();
      } else {
        setError(result.error || "Delete failed");
      }
    } catch {
      setError("An error occurred");
    } finally {
      setLoading(false);
    }
  };

  // Edit state
  const handleEdit = (state: State) => {
    setFormData({
      name: state.name,
      status: state.status as "active" | "inactive",
    });
    setEditingId(state.id);
  };

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">States API Test</h1>

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          {error}
        </div>
      )}

      {/* Create/Update Form */}
      <Card className="mb-8">
        <CardHeader>
          <CardTitle>{editingId ? "Update State" : "Create State"}</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">Name</label>
              <Input
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Status</label>
              <select
                className="w-full border rounded px-3 py-2"
                value={formData.status}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    status: e.target.value as "active" | "inactive",
                  })
                }
              >
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
            </div>
            <div className="flex gap-2">
              <Button type="submit" disabled={loading}>
                {editingId ? "Update" : "Create"}
              </Button>
              {editingId && (
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    setEditingId(null);
                    setFormData({ name: "", status: "active" });
                  }}
                >
                  Cancel
                </Button>
              )}
            </div>
          </form>
        </CardContent>
      </Card>

      {/* Search and Pagination */}
      <Card className="mb-8">
        <CardContent className="pt-6">
          <div className="flex gap-4 items-center">
            <Input
              placeholder="Search states..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <Button onClick={loadStates} disabled={loading}>
              Search
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* States List */}
      <Card>
        <CardHeader>
          <CardTitle>States List</CardTitle>
        </CardHeader>
        <CardContent>
          {loading && <p>Loading...</p>}
          {states && (
            <>
              <div className="space-y-2">
                {states.data.map((state) => (
                  <div
                    key={state.id}
                    className="flex items-center justify-between p-4 border rounded"
                  >
                    <div>
                      <p className="font-medium">{state.name}</p>
                      <p className="text-sm text-gray-500">
                        Code: {state.code || "N/A"} | Status: {state.status}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleEdit(state)}
                      >
                        Edit
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        onClick={() => handleDelete(state.id)}
                      >
                        Delete
                      </Button>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination */}
              <div className="flex justify-between items-center mt-4">
                <p className="text-sm text-gray-500">
                  Page {states.current_page} of {states.last_page} (Total:{" "}
                  {states.total})
                </p>
                <div className="flex gap-2">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => setPage(page - 1)}
                    disabled={page === 1}
                  >
                    Previous
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => setPage(page + 1)}
                    disabled={page === states.last_page}
                  >
                    Next
                  </Button>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
