'use client';

import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { Loader, Plus, X, ChevronDown, Headset, Paperclip, Send } from 'lucide-react';
import { addPublicSupport } from '@/lib/api/client';
import { resetErrorAndMessage, supportUsFailure, supportUsStart, supportUsSuccess } from '@/lib/store/slices/userSlice';
import { SupportFormData, Country } from '@/lib/types';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface SupportUsClientProps {
  logoImage: any;
  countryDataList: Country[];
}

const SupportUsClient: React.FC<SupportUsClientProps> = ({ logoImage, countryDataList }) => {
  const dispatch = useDispatch();
  const router = useRouter();
  
  const userState = useSelector((state: any) => state.user || {});
  const currentCustomer = userState.currentCustomer?.customer || userState.currentCustomer;
  const accessToken = userState.accessToken || userState.currentCustomer?.accessToken;
  const loading = userState.loading;
  
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const countryDropdownRef = useRef<HTMLDivElement>(null);
  const [showCountryDropdown, setShowCountryDropdown] = useState(false);
  const [isClient, setIsClient] = useState(false);
  
  const [supportData, setSupportData] = useState<SupportFormData>({
    fullName: '',
    phone: '',
    email: '',
    subject: '',
    description: '',
    countryDetails: '',
    countryCode: '',
    countryFlag: '',
    countryName: '',
  });
  

  const inputChangeHandler = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = event.target;
    setSupportData((prevData) => {
      let newValue: string = value;
      if (name === 'email') {
        newValue = value.toLowerCase();
      }
      if (name === 'phone') {
        newValue = value.replace(/[^0-9]/g, '');
      }
      return { ...prevData, [name]: newValue };
    });
  };

  const handleAttachClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
      const maxSize = 2 * 1024 * 1024;
      
      if (!allowedTypes.includes(file.type)) {
        toast.error('Only JPG, PNG, JPEG, and PDF files are allowed');
        event.target.value = '';
        return;
      }
      if (file.size > maxSize) {
        toast.error('File size must be less than 2 MB');
        event.target.value = '';
        return;
      }
      setUploadedFile(file);
    }
  };

  const handleRemoveFile = () => {
    setUploadedFile(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const selectCountry = (country: Country) => {
    setSupportData(prev => ({
      ...prev,
      countryDetails: country._id,
      countryCode: country.phonecode || '+91',
      countryFlag: country.countryFlag || '',
      countryName: country.billcountry || '',
    }));
    setShowCountryDropdown(false);
  };

  const validateForm = (): boolean => {
    if (!supportData.subject.trim()) {
      toast.error('Please enter a Subject');
      return false;
    }
    if (!supportData.description.trim()) {
      toast.error('Please enter a description');
      return false;
    }
    if (!supportData.countryDetails) {
      toast.error('Please select a country');
      return false;
    }
    return true;
  };

  const submitForm = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!validateForm()) {
      dispatch(supportUsFailure('Validation failed'));
      return;
    }
    
    const formData = new FormData();
    formData.append('fullName', supportData.fullName);
    formData.append('phone', supportData.phone);
    formData.append('countryDetails', supportData.countryDetails);
    formData.append('email', supportData.email);
    formData.append('subject', supportData.subject);
    formData.append('description', supportData.description);
    formData.append('countryCode', supportData.countryCode);
    
    if (uploadedFile) {
      formData.append('media', uploadedFile);
    }
    
    dispatch(supportUsStart());
    const result = await addPublicSupport(formData, logoImage?.securityKey);
    
    if (result.success) {
      dispatch(supportUsSuccess(result.message));
      toast.success(result.message);
      setSupportData((prev) => ({ ...prev, subject: '', description: '' }));
      setUploadedFile(null);
    } else {
      dispatch(supportUsFailure(result.message));
      toast.error(result.message);
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (countryDropdownRef.current && !countryDropdownRef.current.contains(event.target as Node)) {
        setShowCountryDropdown(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  useEffect(() => {
    setIsClient(true);
  }, []);

  useEffect(() => {
    if (!isClient) return;
    
    const customerData = userState?.currentCustomer?.customer || userState?.currentCustomer;
    
    if (customerData && countryDataList?.length > 0) {
      const fullName = customerData.fullName || customerData.name || '';
      const email = customerData.email || '';
      const phone = customerData.phone ? String(customerData.phone) : '';
      
      setSupportData((prev) => ({
        ...prev,
        fullName: fullName,
        phone: phone,
        email: email,
      }));
      
      const customerCountry = customerData.country || customerData.countryName;
      
      if (customerCountry) {
        const countryData = countryDataList?.find((item) => 
          item?.billcountry?.toLowerCase() === customerCountry.toLowerCase() ||
          item?.countryName?.toLowerCase() === customerCountry.toLowerCase()
        );
        
        if (countryData) {
          setSupportData((prev) => ({
            ...prev,
            countryDetails: countryData._id,
            countryCode: countryData.phonecode || countryData.countryCode || '+91',
            countryFlag: countryData.countryFlag || '',
            countryName: countryData.billcountry || countryData.countryName || '',
          }));
        }
      }
    }
  }, [userState, countryDataList, isClient]);

  useEffect(() => {
    if (isClient) {
      const hasCustomer = userState?.currentCustomer?.customer || userState?.currentCustomer;
      const hasToken = userState?.accessToken || userState?.currentCustomer?.accessToken;
      
      if (!hasCustomer || !hasToken) {
        router.push('/');
      }
    }
  }, [userState, router, isClient]);

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  if (!isClient) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="w-full">
      <div className="flex flex-col gap-6">
        {/* Header Section - Same as Blocked Page */}
        <div className="flex flex-col gap-4">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-primary/10 dark:bg-primary/20 rounded-xl">
                <Headset className="w-6 h-6 text-primary" />
              </div>
              <div>
                <h1 className="text-2xl font-bold text-foreground">Support Us</h1>
                <p className="text-muted-foreground mt-1">
                  Your support helps us improve features, maintain the platform, and empower creators.
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Form Card - Same glass style as Blocked Page cards */}
        <div className="rounded-2xl glass glass-border overflow-hidden">
          <form onSubmit={submitForm} className="p-6 space-y-5">
            {/* Name Field - Readonly */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Full Name</label>
              <input
                readOnly
                value={supportData.fullName || ''}
                type="text"
                placeholder="Your name"
                className="w-full px-4 py-2.5 bg-secondary/30 rounded-xl border border-border focus:outline-none focus:ring-2 focus:ring-primary/30 text-foreground placeholder:text-muted-foreground cursor-not-allowed"
              />
            </div>
            
            {/* Email Field - Readonly */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Email Address</label>
              <input
                readOnly
                value={supportData.email || ''}
                type="email"
                placeholder="Your email"
                className="w-full px-4 py-2.5 bg-secondary/30 rounded-xl border border-border focus:outline-none focus:ring-2 focus:ring-primary/30 text-foreground placeholder:text-muted-foreground cursor-not-allowed"
              />
            </div>
            
            {/* Phone Number with Country Dropdown */}
            <div className="space-y-2" ref={countryDropdownRef}>
              <label className="text-sm font-medium text-foreground">Phone Number</label>
              <div className="flex gap-2">
                <div className="relative">
                  <button
                    type="button"
                    className="h-11 px-3 bg-secondary/30 rounded-xl border border-border flex items-center gap-2 hover:bg-secondary/50 transition-colors"
                    onClick={() => setShowCountryDropdown(!showCountryDropdown)}
                  >
                    {supportData.countryFlag ? (
                      <div className="relative w-6 h-4">
                        <Image
                          src={`${BASE_URL}/uploads/${supportData.countryFlag}`}
                          alt={supportData.countryName || 'Flag'}
                          fill
                          className="object-contain"
                        />
                      </div>
                    ) : (
                      <span className="text-lg">🏳️</span>
                    )}
                    <span className="text-sm text-foreground">{supportData.countryCode || '+91'}</span>
                    <ChevronDown className={`w-4 h-4 text-muted-foreground transition-transform ${showCountryDropdown ? 'rotate-180' : ''}`} />
                  </button>
                  
                  {showCountryDropdown && countryDataList && countryDataList.length > 0 && (
                    <div className="absolute z-50 top-full left-0 mt-1 bg-card border border-border rounded-xl shadow-lg max-h-60 overflow-y-auto min-w-[240px]">
                      {countryDataList.map((country) => (
                        <button
                          key={country._id}
                          type="button"
                          className="flex items-center gap-3 w-full px-3 py-2.5 hover:bg-secondary transition-colors text-left"
                          onClick={() => selectCountry(country)}
                        >
                          {country.countryFlag ? (
                            <div className="relative w-6 h-4">
                              <Image
                                src={`${BASE_URL}/uploads/${country.countryFlag}`}
                                alt={country.billcountry}
                                fill
                                className="object-contain"
                              />
                            </div>
                          ) : (
                            <span className="text-lg">🏳️</span>
                          )}
                          <div className="flex flex-col">
                            <span className="text-sm font-medium text-foreground">{country.billcountry || country.countryName}</span>
                            <span className="text-xs text-muted-foreground">{country.phonecode || country.countryCode}</span>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                
                <div className="flex-1">
                  <input
                    name="phone"
                    value={supportData.phone}
                    onChange={inputChangeHandler}
                    type="tel"
                    placeholder="Enter phone number"
                    className="w-full px-4 py-2.5 bg-secondary/30 rounded-xl border border-border focus:outline-none focus:ring-2 focus:ring-primary/30 text-foreground placeholder:text-muted-foreground"
                  />
                </div>
              </div>
            </div>
            
            {/* Subject Field */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Subject</label>
              <input
                name="subject"
                value={supportData.subject}
                onChange={inputChangeHandler}
                type="text"
                placeholder="What is this regarding?"
                className="w-full px-4 py-2.5 bg-secondary/30 rounded-xl border border-border focus:outline-none focus:ring-2 focus:ring-primary/30 text-foreground placeholder:text-muted-foreground"
              />
            </div>
            
            {/* Description Field */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Description</label>
              <textarea
                name="description"
                value={supportData.description}
                onChange={inputChangeHandler}
                rows={5}
                placeholder="Please describe your issue or suggestion in detail..."
                className="w-full px-4 py-2.5 bg-secondary/30 rounded-xl border border-border focus:outline-none focus:ring-2 focus:ring-primary/30 text-foreground placeholder:text-muted-foreground resize-none"
              />
            </div>
            
            {/* File Attachment */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Attachment (Optional)</label>
              {!uploadedFile ? (
                <button
                  type="button"
                  onClick={handleAttachClick}
                  className="flex items-center gap-2 px-4 py-2.5 bg-secondary/30 rounded-xl border border-border hover:bg-secondary/50 transition-colors w-full"
                >
                  <Paperclip className="w-4 h-4 text-muted-foreground" />
                  <span className="text-sm text-muted-foreground">Attach File</span>
                  <span className="text-xs text-muted-foreground ml-auto">(PDF or Image, max 2MB)</span>
                </button>
              ) : (
                <div className="flex items-center justify-between px-4 py-2.5 bg-secondary/30 rounded-xl border border-border">
                  <span className="text-sm text-foreground truncate flex-1">{uploadedFile.name}</span>
                  <button
                    type="button"
                    onClick={handleRemoveFile}
                    className="text-red-500 hover:text-red-600 transition-colors p-1"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              )}
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileChange}
                accept="image/jpeg,image/jpg,image/png,application/pdf"
                className="hidden"
              />
            </div>
            
            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading}
              className="w-full cursor-pointer md:w-auto px-6 py-2.5 bg-primary hover:bg-primary/90 text-primary-foreground font-medium rounded-xl transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? (
                <>
                  <Loader className="w-4 h-4 animate-spin" />
                  <span>Sending...</span>
                </>
              ) : (
                <>
                  <Send className="w-4 h-4" />
                  <span>Submit Request</span>
                </>
              )}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default SupportUsClient;