'use client';

import React, { useState } from 'react';
import { UserPlus, Eye, EyeOff, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useLinkProvisionInstitutesAdmin, useProvisionInstitutesAdmin } from '@/services/institutes/queries';

interface ProvisionInstituteAdminModalProps {
  institute: {
    id: string;
    name: string;
    code: string;
    sectorId: string;
    address: string | null;
    contactPerson: string | null;
    contactMobile: string | null;
    contactEmail: string | null;
  };
  onClose: () => void;
}

export default function ProvisionInstituteAdminModal({ institute, onClose }: ProvisionInstituteAdminModalProps) {
  const [firstName, setAdminFirstName] = useState('');
  const [lastName, setAdminLastName] = useState('');
  const [email, setAdminEmail] = useState('');
  const [phone, setAdminPhone] = useState('');
  const [password, setAdminPassword] = useState('');

  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const provisionMutation = useLinkProvisionInstitutesAdmin();

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

    if (!firstName.trim() || !lastName.trim() || !email.trim()) {
      setError('Legal administrative identity fields are required.');
      return;
    }

    if (password.length < 8) {
      setError('Root security key check failure (Minimum 8 characters).');
      return;
    }

    // Wrap precisely inside body schema framework expected parameters
    const payload = {
      institute: {
        id: institute.id,
      },
      admin: {
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        email: email.trim().toLowerCase(),
        password: password,
        phone: phone.trim() || null,
      },
    };

    try {
      await provisionMutation.mutateAsync(payload);
      onClose();
    } catch (err: any) {
      setError(err?.response?.data?.message || 'Failed to initialize administrative account records.');
    }
  };

  return (
    <Modal
      onClose={onClose}
      icon={UserPlus}
      iconClassName="text-primary"
      title={`Link Admin Profile: ${institute.name}`}
    >
      <form onSubmit={handleSubmit} className="p-4 space-y-4">
        {error && (
          <div className="p-2.5 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-[10px] font-medium tracking-tight">
            {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">
                First Name
              </label>
              <input
                type="text"
                value={firstName}
                onChange={(e) => setAdminFirstName(e.target.value)}
                placeholder="e.g., Jane"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:border-primary transition-colors"
                required
              />
            </div>
            <div>
              <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
                Last Name
              </label>
              <input
                type="text"
                value={lastName}
                onChange={(e) => setAdminLastName(e.target.value)}
                placeholder="e.g., Doe"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:border-primary transition-colors"
                required
              />
            </div>
          </div>

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

          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
              Mobile Contact Line
            </label>
            <input
              type="text"
              value={phone}
              onChange={(e) => setAdminPhone(e.target.value)}
              placeholder="+91 XXXXX XXXXX"
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:border-primary transition-colors"
            />
          </div>

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

        {/* ACTION BUTTON AXIS */}
        <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 rounded-lg px-3 text-xs font-semibold transition-colors"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            disabled={provisionMutation.isPending}
            className="h-8 rounded-lg px-3 text-xs font-semibold shadow-sm gap-1.5 transition-transform duration-150 active:scale-95"
          >
            <Check className="h-3.5 w-3.5 stroke-[2.5]" />
            <span>{provisionMutation.isPending ? 'Provisioning...' : 'Link Account'}</span>
          </Button>
        </div>
      </form>
    </Modal>
  );
}