import React, { useState, useEffect } from 'react';
import api from '../utils/api';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from './ui/dialog';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { toast } from 'sonner';
import { Loader2, Mail, Copy, Check } from 'lucide-react';

const InviteStaffDialog = ({ open, onOpenChange, onSuccess }) => {
  const [formData, setFormData] = useState({
    email: '',
    first_name: '',
    last_name: '',
    phone: '',
    role: 'admin'
  });
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [invitationUrl, setInvitationUrl] = useState(null);
  const [copied, setCopied] = useState(false);
  const [roles, setRoles] = useState([]);
  const [loadingRoles, setLoadingRoles] = useState(false);

  // Fetch roles when dialog opens
  useEffect(() => {
    if (open) {
      fetchRoles();
    }
  }, [open]);

  const fetchRoles = async () => {
    setLoadingRoles(true);
    try {
      // New endpoint returns roles based on user's permission level
      // Superadmin: all roles
      // Admin: admin, finance, and non-elevated custom roles
      const response = await api.get('/admin/roles/assignable');
      setRoles(response.data);
    } catch (error) {
      console.error('Failed to fetch assignable roles:', error);
      toast.error('Failed to load roles. Please try again.');
    } finally {
      setLoadingRoles(false);
    }
  };

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: null }));
    }
  };

  const validate = () => {
    const newErrors = {};

    if (!formData.email) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Invalid email format';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validate()) {
      return;
    }

    setLoading(true);

    try {
      const response = await api.post('/admin/users/invite', formData);
      toast.success('Invitation sent successfully');

      // Show invitation URL
      setInvitationUrl(response.data.invitation_url);

      // Don't close dialog yet - show invitation URL first
      if (onSuccess) onSuccess();
    } catch (error) {
      const errorMessage = error.response?.data?.detail || 'Failed to send invitation';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(invitationUrl);
    setCopied(true);
    toast.success('Invitation link copied to clipboard');
    setTimeout(() => setCopied(false), 2000);
  };

  const handleClose = () => {
    // Reset form
    setFormData({
      email: '',
      first_name: '',
      last_name: '',
      phone: '',
      role: 'admin'
    });
    setInvitationUrl(null);
    setCopied(false);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[600px] rounded-2xl overflow-y-auto max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="text-2xl text-[var(--purple-ink)] flex items-center gap-2" style={{ fontFamily: "'Inter', sans-serif" }}>
            <Mail className="h-6 w-6" />
            {invitationUrl ? 'Invitation Sent' : 'Invite Staff Member'}
          </DialogTitle>
          <DialogDescription className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            {invitationUrl
              ? 'The invitation has been sent via email. You can also copy the link below.'
              : 'Send an email invitation to join as staff. They will set their own password.'}
          </DialogDescription>
        </DialogHeader>

        {invitationUrl ? (
          // Show invitation URL after successful send
          <div className="py-4">
            <Label className="text-[var(--purple-ink)] mb-2 block">Invitation Link (expires in 7 days)</Label>
            <div className="flex gap-2">
              <Input
                value={invitationUrl}
                readOnly
                className="rounded-xl border-2 border-[var(--neutral-800)] bg-gray-50"
              />
              <Button
                onClick={copyToClipboard}
                className="rounded-xl bg-brand-purple  hover:bg-[var(--purple-ink)] text-white flex-shrink-0"
              >
                {copied ? (
                  <>
                    <Check className="h-4 w-4 mr-2" />
                    Copied
                  </>
                ) : (
                  <>
                    <Copy className="h-4 w-4 mr-2" />
                    Copy
                  </>
                )}
              </Button>
            </div>
          </div>
        ) : (
          // Show invitation form
          <form onSubmit={handleSubmit}>
            <div className="grid gap-6 py-4">
              {/* Email */}
              <div className="grid gap-2">
                <Label htmlFor="email" className="text-[var(--purple-ink)]">
                  Email <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleChange('email', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="staff@example.com"
                />
                {errors.email && (
                  <p className="text-sm text-red-500">{errors.email}</p>
                )}
              </div>

              {/* First Name (Optional) */}
              <div className="grid gap-2">
                <Label htmlFor="first_name" className="text-[var(--purple-ink)]">
                  First Name <span className="text-gray-400">(Optional)</span>
                </Label>
                <Input
                  id="first_name"
                  value={formData.first_name}
                  onChange={(e) => handleChange('first_name', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="Jane"
                />
              </div>

              {/* Last Name (Optional) */}
              <div className="grid gap-2">
                <Label htmlFor="last_name" className="text-[var(--purple-ink)]">
                  Last Name <span className="text-gray-400">(Optional)</span>
                </Label>
                <Input
                  id="last_name"
                  value={formData.last_name}
                  onChange={(e) => handleChange('last_name', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="Doe"
                />
              </div>

              {/* Phone (Optional) */}
              <div className="grid gap-2">
                <Label htmlFor="phone" className="text-[var(--purple-ink)]">
                  Phone <span className="text-gray-400">(Optional)</span>
                </Label>
                <Input
                  id="phone"
                  type="tel"
                  value={formData.phone}
                  onChange={(e) => handleChange('phone', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="(555) 123-4567"
                />
              </div>

              {/* Role */}
              <div className="grid gap-2">
                <Label htmlFor="role" className="text-[var(--purple-ink)]">
                  Role <span className="text-red-500">*</span>
                </Label>
                <Select
                  value={formData.role}
                  onValueChange={(value) => handleChange('role', value)}
                  disabled={loadingRoles}
                >
                  <SelectTrigger className="rounded-xl border-2 border-[var(--neutral-800)]">
                    <SelectValue placeholder={loadingRoles ? "Loading roles..." : "Select a role"} />
                  </SelectTrigger>
                  <SelectContent>
                    {roles.map(role => (
                      <SelectItem key={role.id} value={role.code}>
                        <div className="flex items-center gap-2">
                          <span>{role.name}</span>
                          {role.is_system_role && (
                            <span className="text-xs text-gray-500">(System)</span>
                          )}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {roles.length > 0 && (
                  <p className="text-xs text-gray-500">
                    {roles.find(r => r.code === formData.role)?.description || ''}
                  </p>
                )}
              </div>
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
                className="rounded-xl"
                disabled={loading}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                className="rounded-xl bg-[var(--green-light)] hover:bg-[var(--green-fern)] text-white"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Mail className="h-4 w-4 mr-2" />
                    Send Invitation
                  </>
                )}
              </Button>
            </DialogFooter>
          </form>
        )}

        {invitationUrl && (
          <DialogFooter>
            <Button
              onClick={handleClose}
              className="rounded-xl bg-[var(--green-light)] hover:bg-[var(--green-fern)] text-white"
            >
              Done
            </Button>
          </DialogFooter>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default InviteStaffDialog;
