'use client'

import { useActionState, useState } from 'react'
import { changePassword, deleteUser } from './actions'
import { KeyRound, Trash2, ChevronDown, ChevronUp, Shield } from 'lucide-react'

type User = {
  id: number
  username: string
  role: string
  created_at: Date
}

function ChangePasswordForm({ userId }: { userId: number }) {
  const action = changePassword.bind(null, userId)
  const [state, formAction, isPending] = useActionState(action, undefined)

  return (
    <form action={formAction} className="mt-3 p-4 bg-gray-50 rounded-lg border border-gray-200 space-y-3">
      {state?.success && (
        <p className="text-xs text-green-700 bg-green-50 px-3 py-2 rounded-lg">{state.message}</p>
      )}
      {state?.error && (
        <p className="text-xs text-red-700 bg-red-50 px-3 py-2 rounded-lg">{state.error}</p>
      )}
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-1">Yeni Şifre</label>
          <input
            type="password"
            name="new_password"
            required
            autoComplete="new-password"
            placeholder="Min. 6 karakter"
            className="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
          />
        </div>
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-1">Şifre Tekrar</label>
          <input
            type="password"
            name="confirm_password"
            required
            autoComplete="new-password"
            placeholder="Tekrar giriniz"
            className="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
          />
        </div>
      </div>
      <div className="flex justify-end">
        <button
          type="submit"
          disabled={isPending}
          className="bg-amber-500 hover:bg-amber-600 text-white text-sm font-medium py-1.5 px-4 rounded-lg transition-colors disabled:opacity-70 flex items-center gap-1.5"
        >
          <KeyRound size={14} />
          {isPending ? 'Güncelleniyor...' : 'Şifreyi Güncelle'}
        </button>
      </div>
    </form>
  )
}

function UserRow({ user }: { user: User }) {
  const [expanded, setExpanded] = useState(false)

  async function handleDelete() {
    if (!confirm(`"${user.username}" kullanıcısını silmek istediğinize emin misiniz?`)) return
    const res = await deleteUser(user.id)
    if (res?.error) alert(res.error)
  }

  return (
    <div className="border border-gray-100 rounded-xl overflow-hidden">
      <div className="flex items-center justify-between px-5 py-4 hover:bg-gray-50 transition-colors">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 font-semibold text-sm uppercase">
            {user.username[0]}
          </div>
          <div>
            <p className="font-medium text-gray-900 text-sm">{user.username}</p>
            <p className="text-xs text-gray-400">
              {new Date(user.created_at).toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', year: 'numeric' })}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${
            user.role === 'admin' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-600'
          }`}>
            <Shield size={10} />
            {user.role}
          </span>

          <button
            onClick={() => setExpanded(v => !v)}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-amber-600 bg-amber-50 hover:bg-amber-100 rounded-lg transition-colors font-medium"
          >
            <KeyRound size={13} />
            Şifre
            {expanded ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
          </button>

          <button
            onClick={handleDelete}
            className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
            title="Kullanıcıyı Sil"
          >
            <Trash2 size={16} />
          </button>
        </div>
      </div>

      {expanded && <ChangePasswordForm userId={user.id} />}
    </div>
  )
}

export default function UserList({ users }: { users: User[] }) {
  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
      <h2 className="text-lg font-semibold text-gray-800 mb-4">Mevcut Kullanıcılar ({users.length})</h2>
      {users.length === 0 ? (
        <p className="text-sm text-gray-500 text-center py-6">Henüz kullanıcı yok.</p>
      ) : (
        <div className="space-y-3">
          {users.map(user => (
            <UserRow key={user.id} user={user} />
          ))}
        </div>
      )}
    </div>
  )
}
