"use client";

import { useState, useEffect, useCallback } from "react";
import { MapPin, Stethoscope, Phone, Loader2 } from "lucide-react";
import { getDoctorsByWilaya } from "@/app/actions/doctor";
import { algerianWilayas } from "@/lib/constants";

interface Doctor {
  id: string;
  name: string;
  specialization: string;
  phone: string;
}

interface Step4Props {
  wilaya: string;
  doctorId: string;
  skipDoctor: boolean;
  errors: Record<string, string>;
  onChangeWilaya: (wilaya: string) => void;
  onSelectDoctor: (doctorId: string) => void;
  onToggleSkip: (skip: boolean) => void;
}

export default function Step4Doctor({
  wilaya,
  doctorId,
  skipDoctor,
  errors,
  onChangeWilaya,
  onSelectDoctor,
  onToggleSkip,
}: Step4Props) {
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchDoctors = useCallback(async (selectedWilaya: string) => {
    if (!selectedWilaya) {
      setDoctors([]);
      return;
    }
    setLoading(true);
    const result = await getDoctorsByWilaya(selectedWilaya);
    if (result.success && result.doctors) {
      setDoctors(result.doctors);
    } else {
      setDoctors([]);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    if (wilaya) {
      fetchDoctors(wilaya);
    }
  }, [wilaya, fetchDoctors]);

  return (
    <div className="space-y-6">
      <div>
        <label className="mb-1.5 block text-sm font-medium text-zinc-300">
          Wilaya (Province) <span className="text-red-400">*</span>
        </label>
        <div className="relative">
          <MapPin className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500" />
          <select
            value={wilaya}
            onChange={(e) => {
              onChangeWilaya(e.target.value);
              onSelectDoctor("");
            }}
            className={`w-full appearance-none rounded-lg border bg-zinc-900 py-2.5 pl-10 pr-3 text-sm text-zinc-100 outline-none transition-colors focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 ${
              errors.wilaya ? "border-red-500" : "border-zinc-800"
            }`}
          >
            <option value="" disabled className="bg-zinc-900 text-zinc-500">
              Select a wilaya...
            </option>
            {algerianWilayas.map((w) => (
              <option key={w} value={w} className="bg-zinc-900">
                {w}
              </option>
            ))}
          </select>
        </div>
        {errors.wilaya && (
          <p className="mt-1 text-xs text-red-400">{errors.wilaya}</p>
        )}
      </div>

      {wilaya && (
        <div>
          <div className="mb-3 flex items-center justify-between">
            <label className="text-sm font-medium text-zinc-300">
              Available Doctors <span className="text-red-400">*</span>
            </label>
            <label className="inline-flex cursor-pointer items-center gap-2 text-sm text-zinc-400">
              <input
                type="checkbox"
                checked={skipDoctor}
                onChange={(e) => onToggleSkip(e.target.checked)}
                className="h-4 w-4 rounded border-zinc-600 bg-zinc-800 text-indigo-600 focus:ring-indigo-500"
              />
              Skip for now / تخطي هذه الخطوة
            </label>
            {loading && (
              <span className="inline-flex items-center gap-1 text-xs text-zinc-500">
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
                Loading...
              </span>
            )}
          </div>

          {skipDoctor ? (
            <div className="rounded-xl border border-zinc-800 bg-zinc-900/50 p-6 text-center">
              <p className="text-sm text-zinc-400">
                You can assign a doctor later from the patient profile.
              </p>
            </div>
          ) : loading ? (
            <div className="rounded-xl border border-zinc-800 bg-zinc-900/50 p-8 text-center text-sm text-zinc-500">
              Fetching doctors...
            </div>
          ) : doctors.length === 0 ? (
            <div className="rounded-xl border border-zinc-800 bg-zinc-900/50 p-6 text-center">
              <p className="text-sm text-zinc-400">
                No doctors registered in <strong className="text-zinc-200">{wilaya}</strong> yet.
              </p>
              <p className="mt-1 text-xs text-zinc-500">
                Please select a different province or contact your administrator.
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-3">
              {doctors.map((doc) => {
                const selected = doctorId === doc.id;
                return (
                  <button
                    key={doc.id}
                    type="button"
                    onClick={() => onSelectDoctor(doc.id)}
                    className={`flex items-start gap-3 rounded-lg border p-4 text-left transition-colors ${
                      selected
                        ? "border-indigo-500 bg-indigo-500/10"
                        : "border-zinc-800 bg-zinc-900 hover:border-zinc-700"
                    }`}
                  >
                    <div
                      className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${
                        selected
                          ? "border-indigo-500 bg-indigo-500"
                          : "border-zinc-600"
                      }`}
                    >
                      {selected && (
                        <svg
                          className="h-3 w-3 text-white"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                          strokeWidth={3}
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M5 13l4 4L19 7"
                          />
                        </svg>
                      )}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <Stethoscope className="h-4 w-4 text-zinc-400" />
                        <span className="text-sm font-semibold text-zinc-100">
                          {doc.name}
                        </span>
                      </div>
                      <p className="mt-0.5 text-xs text-zinc-400">
                        {doc.specialization}
                      </p>
                      <div className="mt-1.5 flex items-center gap-1.5 text-xs text-zinc-500">
                        <Phone className="h-3 w-3" />
                        {doc.phone}
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
          {errors.doctorId && (
            <p className="mt-2 text-xs text-red-400">{errors.doctorId}</p>
          )}
        </div>
      )}
    </div>
  );
}

