import React, { useEffect, useState, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import api from '../../utils/api';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Avatar, AvatarImage, AvatarFallback } from '../../components/ui/avatar';
import { Input } from '../../components/ui/input';
import { ArrowLeft, Mail, Phone, MapPin, Calendar, Lock, AlertTriangle, Camera, Upload, Trash2, Shield } from 'lucide-react';
import { toast } from 'sonner';
import ConfirmationDialog from '../../components/ConfirmationDialog';
import ChangeRoleDialog from '../../components/ChangeRoleDialog';
import StatusBadge from '../../components/StatusBadge';
import TransactionHistory from '../../components/TransactionHistory';
import AdminPaymentMethodsPanel from '../../components/admin/AdminPaymentMethodsPanel';

const AdminUserView = () => {
  const { userId } = useParams();
  const navigate = useNavigate();
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [resetPasswordLoading, setResetPasswordLoading] = useState(false);
  const [resendVerificationLoading, setResendVerificationLoading] = useState(false);
  const [transactions, setTransactions] = useState({ subscriptions: [], donations: [] });
  const [transactionsLoading, setTransactionsLoading] = useState(true);
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [pendingAction, setPendingAction] = useState(null);
  const [uploadingPhoto, setUploadingPhoto] = useState(false);
  const [maxFileSizeMB, setMaxFileSizeMB] = useState(50);
  const [maxFileSizeBytes, setMaxFileSizeBytes] = useState(52428800);
  const [memberSince, setMemberSince] = useState('');
  const [memberSinceSaving, setMemberSinceSaving] = useState(false);
  const fileInputRef = useRef(null);
  const [changeRoleDialogOpen, setChangeRoleDialogOpen] = useState(false);

  const formatLocalDateInputValue = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const formatDateInputValue = (value) => {
    if (!value) return '';
    if (typeof value === 'string') {
      if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
        return value;
      }
      const parsed = new Date(value);
      if (Number.isNaN(parsed.getTime())) {
        return value.slice(0, 10);
      }
      return formatLocalDateInputValue(parsed);
    }
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return '';
    return formatLocalDateInputValue(parsed);
  };

  const formatDateDisplayValue = (value) => {
    if (!value) return 'N/A';
    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
      const [year, month, day] = value.split('-').map(Number);
      return new Date(year, month - 1, day).toLocaleDateString();
    }
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return 'N/A';
    return parsed.toLocaleDateString();
  };

  useEffect(() => {
    fetchConfig();
    fetchUserProfile();
    fetchTransactions();
  }, [userId]);

  useEffect(() => {
    if (user) {
      setMemberSince(formatDateInputValue(user.member_since));
    }
  }, [user]);

  const fetchUserProfile = async () => {
    try {
      const response = await api.get(`/admin/users/${userId}`);
      setUser(response.data);
    } catch (error) {
      toast.error('Failed to load user profile');
      navigate('/admin/members');
    } finally {
      setLoading(false);
    }
  };

  const fetchTransactions = async () => {
    try {
      setTransactionsLoading(true);
      const response = await api.get(`/admin/users/${userId}/transactions`);
      setTransactions(response.data);
    } catch (error) {
      console.error('Failed to fetch transactions:', error);
    } finally {
      setTransactionsLoading(false);
    }
  };

  const fetchConfig = async () => {
    try {
      const response = await api.get('/config');
      setMaxFileSizeMB(response.data.max_file_size_mb);
      setMaxFileSizeBytes(response.data.max_file_size_bytes);
    } catch (error) {
      console.error('Failed to fetch config, using defaults:', error);
    }
  };

  const handlePhotoUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      toast.error('Please select an image file');
      return;
    }

    // Validate file size
    if (file.size > maxFileSizeBytes) {
      toast.error(`File size must be less than ${maxFileSizeMB}MB`);
      return;
    }

    setUploadingPhoto(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await api.post(`/admin/users/${userId}/upload-photo`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });

      // Update user state with new photo URL
      setUser(prev => ({
        ...prev,
        profile_photo_url: response.data.profile_photo_url
      }));

      toast.success('Profile photo updated successfully');
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to upload photo');
    } finally {
      setUploadingPhoto(false);
      // Reset file input
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handlePhotoDelete = async () => {
    if (!user?.profile_photo_url) return;

    setUploadingPhoto(true);
    try {
      await api.delete(`/admin/users/${userId}/delete-photo`);

      // Update user state to remove photo URL
      setUser(prev => ({
        ...prev,
        profile_photo_url: null
      }));

      toast.success('Profile photo deleted successfully');
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to delete photo');
    } finally {
      setUploadingPhoto(false);
    }
  };

  const handleResetPasswordRequest = () => {
    setPendingAction({ type: 'reset_password' });
    setConfirmDialogOpen(true);
  };

  const handleResendVerificationRequest = () => {
    setPendingAction({ type: 'resend_verification' });
    setConfirmDialogOpen(true);
  };

  const confirmAction = async () => {
    if (!pendingAction) return;

    const { type } = pendingAction;
    setConfirmDialogOpen(false);

    if (type === 'reset_password') {
      setResetPasswordLoading(true);
      try {
        await api.put(`/admin/users/${userId}/reset-password`, {
          force_change: true
        });
        toast.success(`Password reset email sent to ${user.email}`);
      } catch (error) {
        const errorMessage = error.response?.data?.detail || 'Failed to reset password';
        toast.error(errorMessage);
      } finally {
        setResetPasswordLoading(false);
        setPendingAction(null);
      }
    } else if (type === 'resend_verification') {
      setResendVerificationLoading(true);
      try {
        await api.post(`/admin/users/${userId}/resend-verification`);
        toast.success(`Verification email sent to ${user.email}`);
        // Refresh user data to get updated email_verified status if changed
        await fetchUserProfile();
      } catch (error) {
        const errorMessage = error.response?.data?.detail || 'Failed to send verification email';
        toast.error(errorMessage);
      } finally {
        setResendVerificationLoading(false);
        setPendingAction(null);
      }
    }
  };

  const handleMemberSinceSave = async () => {
    if (!user) return;
    setMemberSinceSaving(true);
    try {
      const payload = {
        member_since: memberSince ? memberSince : null
      };
      const response = await api.put(`/admin/users/${userId}`, payload);
      setUser(prev => ({
        ...prev,
        ...(response?.data || {}),
        member_since: payload.member_since
      }));
      toast.success('Member since updated successfully');
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to update member since');
    } finally {
      setMemberSinceSaving(false);
    }
  };

  const getActionMessage = () => {
    if (!pendingAction || !user) return {};

    const { type } = pendingAction;
    const userName = `${user.first_name} ${user.last_name}`;

    if (type === 'reset_password') {
      return {
        title: 'Reset Password?',
        description: `This will send a temporary password to ${user.email}. ${userName} will be required to change it on their next login.`,
        variant: 'warning',
        confirmText: 'Yes, Reset Password',
      };
    }

    if (type === 'resend_verification') {
      return {
        title: 'Resend Verification Email?',
        description: `This will send a new verification email to ${user.email}. ${userName} will need to click the link to verify their email address.`,
        variant: 'info',
        confirmText: 'Yes, Resend Email',
      };
    }

    return {};
  };

  const handleRoleChanged = () => {
    // Refresh user data after role change
    fetchUserProfile();
  };

  if (loading) return <div>Loading...</div>;
  if (!user) return null;

  const joinedDate = user.created_at;
  const memberSinceBaseline = formatDateInputValue(user.member_since);
  const memberSinceHasChanges = memberSince !== memberSinceBaseline;

  return (
    <>
      {/* Back Button */}
      <Button
        variant="ghost"
        onClick={() => navigate(-1)}
        className="mb-6"
      >
        <ArrowLeft className="h-4 w-4 mr-2" />
        Back
      </Button>

      {/* User Profile Header */}
      <Card className="p-8 bg-background rounded-2xl border border-[var(--neutral-800)] mb-8">
        <div className="flex items-start gap-6">
          {/* Avatar */}
          <Avatar className="h-24 w-24 border-4 border-[var(--neutral-800)]">
            <AvatarImage src={user.profile_photo_url} alt={`${user.first_name} ${user.last_name}`} />
            <AvatarFallback className="bg-[var(--neutral-800)] text-[var(--purple-ink)] font-semibold text-3xl">
              {user.first_name?.[0]}{user.last_name?.[0]}
            </AvatarFallback>
          </Avatar>

          {/* User Info */}
          <div className="flex-1">
            <div className="flex items-center gap-4 mb-4">
              <h1 className="text-3xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                {user.first_name} {user.last_name}
              </h1>
              {/* Status & Role Badges */}
              <StatusBadge status={user.status} />
              <StatusBadge status={user.role} />
             
            </div>

            {/* Contact Info */}
            <div className="grid md:grid-cols-2 gap-4 text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              <div className="flex items-center gap-2">
                <Mail className="h-4 w-4" />
                <span>{user.email}</span>
              </div>
              <div className="flex items-center gap-2">
                <Phone className="h-4 w-4" />
                <span>{user.phone}</span>
              </div>
              <div className="flex items-center gap-2">
                <MapPin className="h-4 w-4" />
                <span>{user.city}, {user.state} {user.zipcode}</span>
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4" />
                <span>Registered: {formatDateDisplayValue(joinedDate)}</span>
              </div>
            </div>
          </div>
        </div>
      </Card>

      {/* Admin Actions */}
      <Card className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)] mb-8">
        <h2 className="text-lg font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
          Admin Actions
        </h2>
        <div className="flex flex-wrap gap-3">
          <Button
            onClick={handleResetPasswordRequest}
            disabled={resetPasswordLoading}
            variant="outline"
            className="border-2 border-brand-purple  text-brand-purple  hover:bg-[var(--lavender-300)] rounded-full px-4 py-2 disabled:opacity-50"
          >
            <Lock className="h-4 w-4 mr-2" />
            {resetPasswordLoading ? 'Resetting...' : 'Reset Password'}
          </Button>

          <Button
            onClick={() => setChangeRoleDialogOpen(true)}
            variant="outline"
            className="border-2 border-brand-purple text-brand-purple hover:bg-[var(--lavender-300)] rounded-full px-4 py-2"
          >
            <Shield className="h-4 w-4 mr-2" />
            Change Role
          </Button>

          {!user.email_verified && (
            <Button
              onClick={handleResendVerificationRequest}
              disabled={resendVerificationLoading}
              variant="outline"
              className="border-2 border-[var(--orange-light)] text-[var(--orange-light)] hover:bg-[#FFF3E0] rounded-full px-4 py-2 disabled:opacity-50"
            >
              <Mail className="h-4 w-4 mr-2" />
              {resendVerificationLoading ? 'Sending...' : 'Resend Verification Email'}
            </Button>
          )}

          {/* Profile Photo Management */}
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={handlePhotoUpload}
            className="hidden"
          />

          <Button
            onClick={() => fileInputRef.current?.click()}
            disabled={uploadingPhoto}
            variant="outline"
            className="border-2 border-[var(--green-light)] text-[var(--green-light)] hover:bg-[var(--green-bg)] rounded-full px-4 py-2 disabled:opacity-50"
          >
            <Upload className="h-4 w-4 mr-2" />
            {uploadingPhoto ? 'Uploading...' : 'Upload Photo'}
          </Button>

          {user.profile_photo_url && (
            <Button
              onClick={handlePhotoDelete}
              disabled={uploadingPhoto}
              variant="outline"
              className="border-2 border-red-500 text-red-500 hover:bg-red-50 rounded-full px-4 py-2 disabled:opacity-50"
            >
              <Trash2 className="h-4 w-4 mr-2" />
              Delete Photo
            </Button>
          )}

          <div className="flex items-center gap-2 text-sm text-brand-purple  ml-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            <AlertTriangle className="h-4 w-4" />
            <span>User will receive a temporary password via email</span>
          </div>
        </div>
      </Card>

      {/* Payment Methods Panel */}
      <div className="mb-8">
        <AdminPaymentMethodsPanel
          userId={userId}
          userName={`${user.first_name} ${user.last_name}`}
        />
      </div>

      {/* Additional Details */}
      <Card className="p-8 bg-background rounded-2xl border border-[var(--neutral-800)]">
        <h2 className="text-2xl font-semibold text-[var(--purple-ink)] mb-6" style={{ fontFamily: "'Inter', sans-serif" }}>
          Additional Information
        </h2>

        <div className="grid md:grid-cols-2 gap-6">
          <div>
            <label className="text-sm font-medium text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Address</label>
            <p className="text-[var(--purple-ink)] mt-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{user.address}</p>
          </div>

          <div>
            <label className="text-sm font-medium text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Date of Birth</label>
            <p className="text-[var(--purple-ink)] mt-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              {formatDateDisplayValue(user.date_of_birth)}
            </p>
          </div>

          <div>
            <label className="text-sm font-medium text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Member Since</label>
            <div className="mt-1 flex flex-wrap items-center gap-2">
              <Input
                type="date"
                value={memberSince}
                onChange={(e) => setMemberSince(e.target.value)}
                className="max-w-[200px] border-[var(--neutral-800)]"
              />
              <Button
                type="button"
                size="sm"
                onClick={handleMemberSinceSave}
                disabled={memberSinceSaving || !memberSinceHasChanges}
                className="bg-[var(--neutral-800)] text-[var(--purple-ink)] hover:bg-background"
              >
                {memberSinceSaving ? 'Saving...' : 'Save'}
              </Button>
            </div>
          </div>

          {user.partner_first_name && (
            <div>
              <label className="text-sm font-medium text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Partner</label>
              <p className="text-[var(--purple-ink)] mt-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                {user.partner_first_name} {user.partner_last_name}
              </p>
            </div>
          )}

          {user.referred_by_member_name && (
            <div>
              <label className="text-sm font-medium text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Referred By</label>
              <p className="text-[var(--purple-ink)] mt-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{user.referred_by_member_name}</p>
            </div>
          )}

          {user.lead_sources && user.lead_sources.length > 0 && (
            <div className="md:col-span-2">
              <label className="text-sm font-medium text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Lead Sources</label>
              <div className="flex flex-wrap gap-2 mt-2">
                {user.lead_sources.map((source, idx) => (
                  <Badge key={idx} variant="outline">{source}</Badge>
                ))}
              </div>
            </div>
          )}
        </div>
      </Card>

      {/* Transaction History */}
      <div className="mt-8">
        <TransactionHistory
          subscriptions={transactions.subscriptions}
          donations={transactions.donations}
          totalSubscriptionCents={transactions.total_subscription_amount_cents}
          totalDonationCents={transactions.total_donation_amount_cents}
          loading={transactionsLoading}
          isAdmin={true}
        />
      </div>

      {/* Admin Action Confirmation Dialog */}
      <ConfirmationDialog
        open={confirmDialogOpen}
        onOpenChange={setConfirmDialogOpen}
        onConfirm={confirmAction}
        loading={resetPasswordLoading || resendVerificationLoading}
        {...getActionMessage()}
      />

      {/* Change Role Dialog */}
      <ChangeRoleDialog
        open={changeRoleDialogOpen}
        onClose={() => setChangeRoleDialogOpen(false)}
        user={user}
        onSuccess={handleRoleChanged}
      />
    </>
  );
};

export default AdminUserView;
