// src/app/(dashboard)/superadmin/districts/_components/TransferOwnershipModal.tsx
'use client';

import React, { useState } from 'react';
import { UserX, ShieldAlert, Eye, EyeOff, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useTransferOwnership } from '@/services/district-sector-assignments/queries';

interface TransferOwnershipModalProps {
  userId: string;
  userFullName: string;
  onClose: () => void;
}

export default function TransferOwnershipModal({ userId, userFullName, onClose }: TransferOwnershipModalProps) {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const transferMutation = useTransferOwnership();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!firstName.trim() || !lastName.trim() || !email.trim() || !password.trim()) {
      setError('All target profile initialization parameters are mandatory.');
      return;
    }

    try {
      await transferMutation.mutateAsync({
        oldUserId: userId,
        newUser: {
          firstName: firstName.trim(),
          lastName: lastName.trim(),
          email: email.trim().toLowerCase(),
          password: password,
        },
      });
      onClose();
    } catch (err: any) {
      setError(err?.response?.data?.message || 'Failed to complete matrix deployment transfer.');
    }
  };

  return (
    <Modal
      onClose={onClose}
      icon={ShieldAlert}
      iconClassName="text-rose-500"
      title={
        <>Transfer Grid Ownership from: <span className="text-rose-500 font-semibold">{userFullName}</span></>
      }
    >
      <form onSubmit={handleSubmit} className="p-4 space-y-4">
        <div className="p-3 bg-rose-500/5 border border-rose-500/10 rounded-xl text-[11px] leading-relaxed text-rose-500 font-medium">
          <strong>CRITICAL OPERATION:</strong> This will clone all active district-sector permissions to the new user, flag this original account profile as inactive, and sever all active system tokens.
        </div>

        {error && (
          <div className="p-2.5 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-[10px] font-medium">
            {error}
          </div>
        )}

        <div className="space-y-3">
          <div className="grid grid-cols-2 gap-2">
            <div>
              <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">Successor First Name</label>
              <input
                type="text"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
                required
              />
            </div>
            <div>
              <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">Successor Last Name</label>
              <input
                type="text"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
                required
              />
            </div>
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">Successor Login Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="successor@domain.com"
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
              required
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">Temporary Security Password</label>
            <div className="relative flex items-center">
              <input
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full text-xs font-mono pl-3 pr-9 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-2.5 p-1 text-muted-foreground/60 hover:text-foreground"
              >
                {showPassword ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
              </button>
            </div>
          </div>
        </div>

        <div className="flex items-center justify-end gap-2 border-t border-border/10 pt-3 mt-4">
          <Button type="button" variant="ghost" onClick={onClose} className="h-8 text-xs font-semibold">
            Cancel Handoff
          </Button>
          <Button
            type="submit"
            disabled={transferMutation.isPending}
            className="h-8 rounded-lg px-3 text-xs font-semibold bg-rose-500 hover:bg-rose-600 text-white gap-1.5"
          >
            <RefreshCw className={`h-3.5 w-3.5 ${transferMutation.isPending ? 'animate-spin' : ''}`} />
            <span>{transferMutation.isPending ? 'Processing Transfer...' : 'Confirm Atomic Shift'}</span>
          </Button>
        </div>
      </form>
    </Modal>
  );
}