'use client';

import React, { useState } from 'react';
import { UserCheck, Shield, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useProvisionDistrictOwner } from '@/services/districts/mutations';

interface ProvisionOwnerModalProps {
  districtId: string;
  districtName: string;
  onClose: () => void;
}

export default function ProvisionOwnerModal({ districtId, districtName, onClose }: ProvisionOwnerModalProps) {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false); // Added visibility state tracking
  const [error, setError] = useState<string | null>(null);
  
  const provisionMutation = useProvisionDistrictOwner();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    
    if (!firstName.trim() || !lastName.trim() || !email.trim() || !password.trim()) {
      setError('Explicit profile authentication matrix fields are required.');
      return;
    }

    try {
      await provisionMutation.mutateAsync({
        districtId,
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        email: email.trim().toLowerCase(),
        phone: phone.trim() || undefined,
        password: password,
      });
      onClose();
    } catch (err: any) {
      setError(err?.response?.data?.message || 'Failed to initialize administrative account records.');
    }
  };

  return (
    <Modal
      onClose={onClose}
      icon={Shield}
      iconClassName="text-amber-500"
      title={
        <>Provision Owner: <span className="text-primary font-mono font-black">{districtName}</span></>
      }
    >
      <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) => setFirstName(e.target.value)}
                placeholder="John"
                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 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) => setLastName(e.target.value)}
                placeholder="Doe"
                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 transition-colors"
                required
              />
            </div>
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">System Login Email Address</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="manager@district.gov"
              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 transition-colors"
              required
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">Contact Phone (Optional)</label>
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(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 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 Security Password</label>
            {/* Added relative layout wrapper context to contain the inline trailing action icon */}
            <div className="relative flex items-center">
              <input
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                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 transition-colors"
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-2.5 p-1 rounded-md text-muted-foreground/60 hover:text-foreground hover:bg-muted/50 transition-colors cursor-pointer"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                {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 bg-amber-500 hover:bg-amber-600 active:scale-95 transition-transform duration-150"
          >
            <UserCheck className="h-3.5 w-3.5 stroke-[2.5]" />
            <span>{provisionMutation.isPending ? 'Provisioning...' : 'Assign Authority'}</span>
          </Button>
        </div>
      </form>
    </Modal>
  );
}