import { useState, useEffect, useCallback } from 'react';
import { Typography, Card, Input, Button, Switch, Spin, Grid, theme, App, Divider } from 'antd';
import {
  UserOutlined,
  LockOutlined,
  EyeOutlined,
  SaveOutlined,
} from '@ant-design/icons';
import { mediaApi } from '@/lib/media-api';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;

interface PrivacySettings {
  showOnlineStatus: boolean | null;
  showCurrentlyWatching: boolean | null;
  showInFriendActivity: boolean | null;
  anonymizePublicComments: boolean | null;
  hidePublicReactions: boolean | null;
  hidePublicFinishes: boolean | null;
  allowFriendRequests: boolean | null;
  closeFriendsOnlyWatching: boolean | null;
}

interface ProfileData {
  name: string | null;
  email: string;
}

const privacyToggles: {
  key: keyof PrivacySettings;
  label: string;
  description: string;
}[] = [
  {
    key: 'showOnlineStatus',
    label: 'Show Online Status',
    description: 'Let others see when you are online',
  },
  {
    key: 'showCurrentlyWatching',
    label: 'Show Currently Watching',
    description: 'Display what video you are watching to friends',
  },
  {
    key: 'showInFriendActivity',
    label: 'Show in Friend Activity',
    description: 'Appear in the friend activity feed',
  },
  {
    key: 'anonymizePublicComments',
    label: 'Anonymize Public Comments',
    description: 'Hide your name on public comments',
  },
  {
    key: 'hidePublicReactions',
    label: 'Hide Public Reactions',
    description: 'Do not show your reactions publicly',
  },
  {
    key: 'hidePublicFinishes',
    label: 'Hide Public Finishes',
    description: 'Hide your video completion status from others',
  },
  {
    key: 'allowFriendRequests',
    label: 'Allow Friend Requests',
    description: 'Let other users send you friend requests',
  },
  {
    key: 'closeFriendsOnlyWatching',
    label: 'Close Friends Only Watching',
    description: 'Only close friends can see what you watch',
  },
];

export default function MySettingsPage() {
  const { token } = theme.useToken();
  const { message } = App.useApp();
  const screens = useBreakpoint();
  const isMobile = !screens.md;

  const [loading, setLoading] = useState(true);
  const [profile, setProfile] = useState<ProfileData>({ name: null, email: '' });
  const [editName, setEditName] = useState('');
  const [savingProfile, setSavingProfile] = useState(false);
  const [privacy, setPrivacy] = useState<PrivacySettings | null>(null);

  // Password fields
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [changingPassword, setChangingPassword] = useState(false);

  const fetchSettings = useCallback(async () => {
    try {
      const { data } = await mediaApi.get('/media/me/settings');
      setProfile(data.profile);
      setEditName(data.profile.name || '');
      setPrivacy(data.privacy);
    } catch {
      // Silent
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleSaveProfile = async () => {
    setSavingProfile(true);
    try {
      const { data } = await mediaApi.put('/media/me/profile', {
        name: editName.trim() || null,
      });
      setProfile(data.profile);
      message.success('Profile updated');
    } catch {
      message.error('Failed to update profile');
    } finally {
      setSavingProfile(false);
    }
  };

  const handleTogglePrivacy = async (key: keyof PrivacySettings, checked: boolean) => {
    // Optimistic update
    setPrivacy((prev) => (prev ? { ...prev, [key]: checked } : prev));
    try {
      await mediaApi.put('/media/me/settings', { [key]: checked });
    } catch {
      // Revert on failure
      setPrivacy((prev) => (prev ? { ...prev, [key]: !checked } : prev));
      message.error('Failed to update setting');
    }
  };

  const handleChangePassword = async () => {
    if (!currentPassword || !newPassword) {
      message.warning('Please fill in all password fields');
      return;
    }
    if (newPassword !== confirmPassword) {
      message.warning('New passwords do not match');
      return;
    }
    if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{12,}$/.test(newPassword)) {
      message.warning('Password must be 12+ characters with uppercase, lowercase, and a digit');
      return;
    }

    setChangingPassword(true);
    try {
      await mediaApi.put('/media/me/password', {
        currentPassword,
        newPassword,
      });
      message.success('Password changed successfully');
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to change password'));
    } finally {
      setChangingPassword(false);
    }
  };

  // Password strength indicator
  const getPasswordStrength = (pw: string): { label: string; color: string; pct: number } => {
    if (!pw) return { label: '', color: '', pct: 0 };
    let score = 0;
    if (pw.length >= 12) score++;
    if (pw.length >= 16) score++;
    if (/[A-Z]/.test(pw)) score++;
    if (/[a-z]/.test(pw)) score++;
    if (/\d/.test(pw)) score++;
    if (/[^A-Za-z0-9]/.test(pw)) score++;

    if (score <= 2) return { label: 'Weak', color: '#ef4444', pct: 25 };
    if (score <= 4) return { label: 'Fair', color: '#f59e0b', pct: 50 };
    if (score <= 5) return { label: 'Good', color: '#22c55e', pct: 75 };
    return { label: 'Strong', color: '#10b981', pct: 100 };
  };

  const strength = getPasswordStrength(newPassword);

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 100 }}>
        <Spin size="large" />
      </div>
    );
  }

  const cardStyle = {
    background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(255,255,255,0.08)',
    borderRadius: 10,
    marginBottom: 24,
  };

  return (
    <div style={{ maxWidth: 640, margin: '0 auto', padding: isMobile ? '16px 8px' : '24px 16px' }}>
      <Title level={3} style={{ margin: '0 0 24px', color: token.colorText }}>
        Settings
      </Title>

      {/* Profile Section */}
      <Card
        size="small"
        title={
          <Text strong style={{ color: token.colorText }}>
            <UserOutlined style={{ marginRight: 8 }} />
            Profile
          </Text>
        }
        style={cardStyle}
        styles={{ body: { padding: 16 } }}
      >
        <div style={{ marginBottom: 16 }}>
          <Text style={{ display: 'block', marginBottom: 6, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
            Name
          </Text>
          <Input
            value={editName}
            onChange={(e) => setEditName(e.target.value)}
            placeholder="Your display name"
            maxLength={100}
            style={{ maxWidth: 400 }}
          />
        </div>
        <div style={{ marginBottom: 16 }}>
          <Text style={{ display: 'block', marginBottom: 6, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
            Email
          </Text>
          <Text style={{ color: 'rgba(255,255,255,0.65)' }}>{profile.email}</Text>
        </div>
        <Button
          type="primary"
          icon={<SaveOutlined />}
          onClick={handleSaveProfile}
          loading={savingProfile}
          disabled={editName.trim() === (profile.name || '')}
          size="small"
        >
          Save Profile
        </Button>
      </Card>

      {/* Password Section */}
      <Card
        size="small"
        title={
          <Text strong style={{ color: token.colorText }}>
            <LockOutlined style={{ marginRight: 8 }} />
            Change Password
          </Text>
        }
        style={cardStyle}
        styles={{ body: { padding: 16 } }}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 400 }}>
          <div>
            <Text style={{ display: 'block', marginBottom: 6, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
              Current Password
            </Text>
            <Input.Password
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              placeholder="Enter current password"
            />
          </div>
          <div>
            <Text style={{ display: 'block', marginBottom: 6, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
              New Password
            </Text>
            <Input.Password
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="Enter new password"
            />
            {newPassword && (
              <div style={{ marginTop: 6 }}>
                <div
                  style={{
                    height: 4,
                    borderRadius: 2,
                    background: 'rgba(255,255,255,0.1)',
                    overflow: 'hidden',
                  }}
                >
                  <div
                    style={{
                      width: `${strength.pct}%`,
                      height: '100%',
                      background: strength.color,
                      borderRadius: 2,
                      transition: 'width 0.3s ease',
                    }}
                  />
                </div>
                <Text style={{ fontSize: 11, color: strength.color }}>{strength.label}</Text>
              </div>
            )}
          </div>
          <div>
            <Text style={{ display: 'block', marginBottom: 6, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
              Confirm New Password
            </Text>
            <Input.Password
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              placeholder="Confirm new password"
              status={confirmPassword && confirmPassword !== newPassword ? 'error' : undefined}
            />
          </div>
          <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)' }}>
            12+ characters, uppercase, lowercase, digit required
          </Text>
          <Button
            type="primary"
            icon={<LockOutlined />}
            onClick={handleChangePassword}
            loading={changingPassword}
            disabled={!currentPassword || !newPassword || !confirmPassword}
            size="small"
            style={{ alignSelf: 'flex-start' }}
          >
            Change Password
          </Button>
        </div>
      </Card>

      {/* Privacy Section */}
      <Card
        size="small"
        title={
          <Text strong style={{ color: token.colorText }}>
            <EyeOutlined style={{ marginRight: 8 }} />
            Privacy
          </Text>
        }
        style={cardStyle}
        styles={{ body: { padding: '8px 16px' } }}
      >
        {privacy &&
          privacyToggles.map((toggle, i) => (
            <div key={toggle.key}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '12px 0',
                }}
              >
                <div style={{ flex: 1, minWidth: 0, marginRight: 16 }}>
                  <Text
                    style={{
                      display: 'block',
                      fontSize: 13,
                      fontWeight: 500,
                      color: token.colorText,
                    }}
                  >
                    {toggle.label}
                  </Text>
                  <Text
                    style={{
                      fontSize: 11,
                      color: 'rgba(255,255,255,0.4)',
                    }}
                  >
                    {toggle.description}
                  </Text>
                </div>
                <Switch
                  checked={privacy[toggle.key] ?? false}
                  onChange={(checked) => handleTogglePrivacy(toggle.key, checked)}
                  size="small"
                />
              </div>
              {i < privacyToggles.length - 1 && (
                <Divider style={{ margin: 0, borderColor: 'rgba(255,255,255,0.06)' }} />
              )}
            </div>
          ))}
      </Card>
    </div>
  );
}
