import React, { useState, useEffect, useRef } from 'react';
import api from '../../utils/api';
import Navbar from '../../components/Navbar';
import MemberFooter from '../../components/MemberFooter';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Input } from '../../components/ui/input';
import { Textarea } from '../../components/ui/textarea';
import { Label } from '../../components/ui/label';
import { Switch } from '../../components/ui/switch';
import { User, Upload, X, Facebook, Instagram, Twitter, Linkedin, Camera, Save, Eye } from 'lucide-react';
import { useToast } from '../../hooks/use-toast';

const MemberProfile = () => {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [profile, setProfile] = useState(null);
  const [formData, setFormData] = useState({
    social_media_facebook: '',
    social_media_instagram: '',
    social_media_twitter: '',
    social_media_linkedin: '',
    show_in_directory: false,
    directory_email: '',
    directory_bio: '',
    directory_address: '',
    directory_phone: '',
    directory_partner_name: ''
  });
  const [previewImage, setPreviewImage] = useState(null);
  const fileInputRef = useRef(null);
  const { toast } = useToast();

  useEffect(() => {
    fetchProfile();
  }, []);

  const fetchProfile = async () => {
    try {
      const response = await api.get('/members/profile');
      setProfile(response.data);

      // Populate form with existing data
      setFormData({
        social_media_facebook: response.data.social_media_facebook || '',
        social_media_instagram: response.data.social_media_instagram || '',
        social_media_twitter: response.data.social_media_twitter || '',
        social_media_linkedin: response.data.social_media_linkedin || '',
        show_in_directory: response.data.show_in_directory || false,
        directory_email: response.data.directory_email || '',
        directory_bio: response.data.directory_bio || '',
        directory_address: response.data.directory_address || '',
        directory_phone: response.data.directory_phone || '',
        directory_partner_name: response.data.directory_partner_name || ''
      });

      if (response.data.profile_photo_url) {
        setPreviewImage(response.data.profile_photo_url);
      }
    } catch (error) {
      console.error('Failed to fetch profile:', error);
      toast({
        title: "Error",
        description: "Failed to load profile. Please try again.",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleSwitchChange = (checked) => {
    setFormData(prev => ({
      ...prev,
      show_in_directory: checked
    }));
  };

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

    // Validate file type
    if (!file.type.startsWith('image/')) {
      toast({
        title: "Invalid File",
        description: "Please upload an image file (JPG, PNG, WebP, or GIF).",
        variant: "destructive"
      });
      return;
    }

    // Validate file size (50MB max)
    if (file.size > 52428800) {
      toast({
        title: "File Too Large",
        description: "Image must be smaller than 50MB.",
        variant: "destructive"
      });
      return;
    }

    setUploading(true);

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

      const response = await api.post('/members/profile/upload-photo', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      setPreviewImage(response.data.profile_photo_url);
      toast({
        title: "Success",
        description: "Profile photo uploaded successfully!"
      });

      // Refresh profile
      await fetchProfile();
    } catch (error) {
      console.error('Failed to upload photo:', error);
      toast({
        title: "Upload Failed",
        description: error.response?.data?.detail || "Failed to upload photo. Please try again.",
        variant: "destructive"
      });
    } finally {
      setUploading(false);
    }
  };

  const handleDeletePhoto = async () => {
    if (!window.confirm('Are you sure you want to delete your profile photo?')) {
      return;
    }

    try {
      await api.delete('/members/profile/delete-photo');
      setPreviewImage(null);
      toast({
        title: "Success",
        description: "Profile photo deleted successfully."
      });

      await fetchProfile();
    } catch (error) {
      console.error('Failed to delete photo:', error);
      toast({
        title: "Error",
        description: "Failed to delete photo. Please try again.",
        variant: "destructive"
      });
    }
  };

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

    try {
      await api.put('/members/profile', formData);
      toast({
        title: "Success",
        description: "Profile updated successfully!"
      });

      await fetchProfile();
    } catch (error) {
      console.error('Failed to update profile:', error);
      toast({
        title: "Error",
        description: "Failed to update profile. Please try again.",
        variant: "destructive"
      });
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <div className="max-w-4xl mx-auto px-6 py-12">
          <div className="text-center py-20">
            <p className="text-[var(--purple-lavender)]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Loading profile...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Navbar />

      <div className="max-w-4xl mx-auto px-6 py-12">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-4xl md:text-5xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Member Profile
          </h1>
          <p className="text-lg text-[var(--purple-lavender)]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Enhance your profile with a photo and social media links.
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-8">
          {/* Profile Photo Section */}
          <Card className="p-8 bg-background border-[var(--neutral-800)] rounded-2xl">
            <h2 className="text-2xl font-semibold text-[var(--purple-ink)] mb-6" style={{ fontFamily: "'Inter', sans-serif" }}>
              Profile Photo
            </h2>

            <div className="flex flex-col md:flex-row items-center gap-8">
              <div className="relative">
                {previewImage ? (
                  <div className="relative">
                    <img
                      src={previewImage}
                      alt="Profile"
                      className="w-40 h-40 rounded-full object-cover border-4 border-[var(--neutral-800)]"
                    />
                    <Button
                      type="button"
                      onClick={handleDeletePhoto}
                      className="absolute -top-2 -right-2 bg-red-500 hover:bg-red-600 text-white rounded-full p-2 w-8 h-8"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ) : (
                  <div className="w-40 h-40 rounded-full bg-[var(--lavender-500)] border-4 border-[var(--neutral-800)] flex items-center justify-center">
                    <User className="h-20 w-20 text-[var(--neutral-800)]" />
                  </div>
                )}
              </div>

              <div className="flex-1">
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handlePhotoUpload}
                  accept="image/*"
                  className="hidden"
                />
                <Button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={uploading}
                  className="bg-[var(--purple-lavender)] hover:bg-[var(--purple-ink)] text-white rounded-xl px-6 py-3 flex items-center gap-2"
                  style={{ fontFamily: "'Inter', sans-serif" }}
                >
                  {uploading ? (
                    <>
                      <Upload className="h-5 w-5 animate-spin" />
                      Uploading...
                    </>
                  ) : (
                    <>
                      <Camera className="h-5 w-5" />
                      {previewImage ? 'Change Photo' : 'Upload Photo'}
                    </>
                  )}
                </Button>
                <p className="text-sm text-[var(--purple-lavender)] mt-3" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  JPG, PNG, WebP, or GIF. Max 50MB.
                </p>
              </div>
            </div>
          </Card>

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

            <div className="space-y-6">
              <div>
                <Label className="flex items-center gap-2 text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  <Facebook className="h-4 w-4 text-[var(--blue-facebook)]" />
                  Facebook Profile URL
                </Label>
                <Input
                  type="url"
                  name="social_media_facebook"
                  value={formData.social_media_facebook}
                  onChange={handleInputChange}
                  placeholder="https://facebook.com/yourprofile"
                  className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                  style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                />
              </div>

              <div>
                <Label className="flex items-center gap-2 text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  <Instagram className="h-4 w-4 text-[var(--red-instagram)]" />
                  Instagram Profile URL
                </Label>
                <Input
                  type="url"
                  name="social_media_instagram"
                  value={formData.social_media_instagram}
                  onChange={handleInputChange}
                  placeholder="https://instagram.com/yourprofile"
                  className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                  style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                />
              </div>

              <div>
                <Label className="flex items-center gap-2 text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  <Twitter className="h-4 w-4 text-[var(--blue-twitter)]" />
                  Twitter/X Profile URL
                </Label>
                <Input
                  type="url"
                  name="social_media_twitter"
                  value={formData.social_media_twitter}
                  onChange={handleInputChange}
                  placeholder="https://twitter.com/yourprofile"
                  className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                  style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                />
              </div>

              <div>
                <Label className="flex items-center gap-2 text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  <Linkedin className="h-4 w-4 text-[var(--blue-linkedin)]" />
                  LinkedIn Profile URL
                </Label>
                <Input
                  type="url"
                  name="social_media_linkedin"
                  value={formData.social_media_linkedin}
                  onChange={handleInputChange}
                  placeholder="https://linkedin.com/in/yourprofile"
                  className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                  style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                />
              </div>
            </div>
          </Card>

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

            <div className="space-y-6">
              <div className="flex items-center justify-between p-4 bg-[var(--lavender-500)] rounded-xl">
                <div className="flex-1">
                  <Label className="text-[var(--purple-ink)] font-medium flex items-center gap-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                    <Eye className="h-4 w-4 text-[var(--purple-lavender)]" />
                    Show in Members Directory
                  </Label>
                  <p className="text-sm text-[var(--purple-lavender)] mt-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    Allow other members to see your profile in the directory
                  </p>
                </div>
                <Switch
                  checked={formData.show_in_directory}
                  onCheckedChange={handleSwitchChange}
                  className="data-[state=checked]:bg-[var(--purple-lavender)]"
                />
              </div>

              {formData.show_in_directory && (
                <>
                  <div>
                    <Label className="text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      Directory Email (visible to members)
                    </Label>
                    <Input
                      type="email"
                      name="directory_email"
                      value={formData.directory_email}
                      onChange={handleInputChange}
                      placeholder="public.email@example.com"
                      className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                      style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                    />
                  </div>

                  <div>
                    <Label className="text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      Bio (visible to members)
                    </Label>
                    <Textarea
                      name="directory_bio"
                      value={formData.directory_bio}
                      onChange={handleInputChange}
                      placeholder="Tell other members about yourself..."
                      rows={4}
                      className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                      style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                    />
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <Label className="text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                        Directory Address (optional)
                      </Label>
                      <Input
                        type="text"
                        name="directory_address"
                        value={formData.directory_address}
                        onChange={handleInputChange}
                        placeholder="123 Main St, City, State"
                        className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                        style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                      />
                    </div>

                    <div>
                      <Label className="text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                        Directory Phone (optional)
                      </Label>
                      <Input
                        type="tel"
                        name="directory_phone"
                        value={formData.directory_phone}
                        onChange={handleInputChange}
                        placeholder="(555) 123-4567"
                        className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                        style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                      />
                    </div>
                  </div>

                  <div>
                    <Label className="text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      Partner Name (if applicable)
                    </Label>
                    <Input
                      type="text"
                      name="directory_partner_name"
                      value={formData.directory_partner_name}
                      onChange={handleInputChange}
                      placeholder="Partner's name"
                      className="border-[var(--neutral-800)] rounded-xl focus:border-[var(--purple-lavender)] focus:ring-[var(--purple-lavender)]"
                      style={{ fontFamily: "'Nunito Sans', sans-serif" }}
                    />
                  </div>
                </>
              )}
            </div>
          </Card>

          {/* Submit Button */}
          <div className="flex justify-end">
            <Button
              type="submit"
              disabled={saving}
              className="bg-[var(--orange-light)] hover:bg-[var(--orange-apricot)] text-white rounded-xl px-8 py-3 text-lg"
              style={{ fontFamily: "'Inter', sans-serif" }}
            >
              {saving ? (
                'Saving...'
              ) : (
                <>
                  <Save className="h-5 w-5 mr-2" />
                  Save Profile
                </>
              )}
            </Button>
          </div>
        </form>
      </div>
      <MemberFooter />
    </div>
  );
};

export default MemberProfile;
