import { useState } from 'react';
import {
  Save,
  Sliders,
  Bell,
  Lock,
  Shield,
  Megaphone,
  Building,
  CheckCircle2,
  AlertTriangle,
  HelpCircle,
  LogOut,
  Eye,
  EyeOff
} from 'lucide-react';
import { Button } from '@astryxdesign/core/Button';
import { Card } from '@astryxdesign/core/Card';
import { List, ListItem } from '@astryxdesign/core/List';
import { Text, Heading } from '@astryxdesign/core/Text';
import { TextInput } from '@astryxdesign/core/TextInput';
import { Selector } from '@astryxdesign/core/Selector';
import { Switch } from '@astryxdesign/core/Switch';
import { Badge } from '@astryxdesign/core/Badge';

import PageHeader from '@/components/PageHeader';

const TIMEZONES = ['Asia/Kolkata (IST)', 'Asia/Dubai (GST)', 'UTC', 'America/New_York (EST)'];
const LANGUAGES = ['English', 'हिन्दी (Hindi)', 'العربية (Arabic)'];

const INITIAL_GENERAL = {
  orgName: 'Doormile Technologies',
  supportEmail: 'support@doormile.in',
  contact: '+91 63749 46729',
  timezone: TIMEZONES[0],
  language: LANGUAGES[0]
};
const INITIAL_NOTIFY = {
  newClient: true, contractStatus: true, teamAccess: false, databaseSync: true, emailAlerts: true, smsAlerts: false
};
const INITIAL_SECURITY = { currentPassword: '', newPassword: '', confirmPassword: '', twoFactor: false };

const NAV = [
  { icon: Sliders, label: 'General', desc: 'Organisation profile' },
  { icon: Bell, label: 'Notifications', desc: 'Alerts & channels' },
  { icon: Lock, label: 'Security', desc: 'Password & 2FA' }
];

const NOTIFY_ROWS = [
  { k: 'newClient', t: 'New client onboarded', d: 'Notify when a new client is added to the system' },
  { k: 'contractStatus', t: 'Contract status', d: 'When a client contract becomes active or expires' },
  { k: 'teamAccess', t: 'Team access', d: 'When a new team member is granted or revoked access' },
  { k: 'databaseSync', t: 'Database sync', d: 'Alerts for vector database synchronization events' }
];

const STRENGTH = [
  { label: 'Too weak', color: '#ef4444' },
  { label: 'Weak', color: '#ef4444' },
  { label: 'Fair', color: '#f59e0b' },
  { label: 'Good', color: '#3b82f6' },
  { label: 'Strong', color: '#10b981' }
];

const scorePassword = (pw) => {
  let s = 0;
  if (pw.length >= 8) s++;
  if (/[a-z]/.test(pw) && /[A-Z]/.test(pw)) s++;
  if (/\d/.test(pw)) s++;
  if (/[^A-Za-z0-9]/.test(pw)) s++;
  return s;
};

function Section({ icon: Icon, title, subtitle, danger = false, children }) {
  return (
    <Card style={{ padding: '0', borderRadius: '16px', border: danger ? '1px solid #fca5a5' : '1px solid rgba(5, 54, 89, 0.08)', backgroundColor: '#ffffff', overflow: 'hidden' }}>
      <div
        style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          padding: '18px 24px',
          borderBottom: '1px solid rgba(5, 54, 89, 0.06)',
          background: danger ? 'linear-gradient(90deg, rgba(239, 68, 68, 0.04) 0%, #ffffff 72%)' : 'linear-gradient(90deg, rgba(192, 18, 39, 0.04) 0%, #ffffff 72%)',
          gap: '12px'
        }}
      >
        <div style={{ width: '40px', height: '40px', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: danger ? 'rgba(239, 68, 68, 0.08)' : 'rgba(192, 18, 39, 0.08)', color: danger ? '#ef4444' : '#C01227' }}>
          <Icon size={18} />
        </div>
        <div>
          <Heading level={5}>{title}</Heading>
          {subtitle && <Text type="supporting" color="secondary">{subtitle}</Text>}
        </div>
      </div>
      <div style={{ padding: '4px 24px' }}>{children}</div>
    </Card>
  );
}

function Row({ label, description, controlAlign = 'stretch', children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', padding: '16px 0', borderBottom: '1px solid #f1f5f9', flexWrap: 'wrap', gap: '12px' }} className="settings-row">
      <div style={{ display: 'flex', flexDirection: 'column', gap: '2px', width: '240px', flexShrink: 0 }}>
        <Text type="body" weight="semibold">{label}</Text>
        {description && <Text type="supporting" color="secondary">{description}</Text>}
      </div>
      <div
        style={{
          flexGrow: 1,
          minWidth: '220px',
          display: controlAlign === 'end' ? 'flex' : 'block',
          justifyContent: controlAlign === 'end' ? 'flex-end' : undefined
        }}
      >
        {children}
      </div>
    </div>
  );
}

function PasswordField({ label, value, onChange }) {
  const [show, setShow] = useState(false);
  return (
    <div style={{ position: 'relative', width: '100%' }}>
      <TextInput
        label={label}
        isLabelHidden
        type={show ? 'text' : 'password'}
        placeholder={label}
        value={value}
        onChange={onChange}
      />
      <button
        type="button"
        onClick={() => setShow((s) => !s)}
        aria-label={show ? 'Hide password' : 'Show password'}
        style={{
          position: 'absolute',
          right: '10px',
          bottom: 0,
          height: '32px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: 'none',
          border: 'none',
          cursor: 'pointer',
          color: '#64748b',
          padding: 0,
          zIndex: 5
        }}
      >
        {show ? <EyeOff size={16} /> : <Eye size={16} />}
      </button>
    </div>
  );
}

export default function Settings() {
  const [tab, setTab] = useState(0);
  const [toast, setToast] = useState(false);
  const [dirty, setDirty] = useState(false);

  const [general, setGeneral] = useState(INITIAL_GENERAL);
  const [notify, setNotify] = useState(INITIAL_NOTIFY);
  const [security, setSecurity] = useState(INITIAL_SECURITY);

  const setG = (k) => (val) => { setGeneral((p) => ({ ...p, [k]: val })); setDirty(true); };
  const setN = (k) => (val) => { setNotify((p) => ({ ...p, [k]: val })); setDirty(true); };
  const setSText = (k) => (val) => { setSecurity((p) => ({ ...p, [k]: val })); setDirty(true); };

  const save = () => { setToast(true); setDirty(false); setTimeout(() => setToast(false), 2500); };
  const discard = () => {
    setGeneral(INITIAL_GENERAL);
    setNotify(INITIAL_NOTIFY);
    setSecurity(INITIAL_SECURITY);
    setDirty(false);
  };

  const pwScore = scorePassword(security.newPassword);
  const pwMeta = STRENGTH[pwScore];
  const mismatch = security.confirmPassword && security.newPassword !== security.confirmPassword;

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif' }}>
      <PageHeader
        title="Settings"
        action={
          <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
            {dirty && <Badge variant="warning" label="Unsaved changes" />}
            <Button variant="ghost" onClick={discard} label="Discard" />
            <Button variant="primary" icon={<Save size={14} />} onClick={save} label="Save Changes" />
          </div>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr', lg: 'repeat(12, 1fr)', gap: '24px', marginTop: '24px' }} className="responsive-row">
        {/* Sidebar */}
        <div style={{ gridColumn: 'span 3' }} className="col-span-3">
          <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
            <Card style={{ padding: '8px' }}>
              <List density="spacious">
                {NAV.map((item, i) => (
                  <ListItem
                    key={item.label}
                    label={item.label}
                    description={item.desc}
                    startContent={<item.icon size={16} />}
                    isSelected={tab === i}
                    onClick={() => setTab(i)}
                  />
                ))}
              </List>
            </Card>

            <Card style={{ padding: '20px', backgroundColor: 'rgba(192, 18, 39, 0.05)', border: '1px solid rgba(192, 18, 39, 0.1)' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                <div style={{ width: '38px', height: '38px', borderRadius: '8px', backgroundColor: '#C01227', color: '#ffffff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <HelpCircle size={16} />
                </div>
                <div>
                  <Text type="body" weight="bold" color="accent">Need a hand?</Text>
                  <div style={{ marginTop: '2px' }}>
                    <Text type="supporting" color="accent">Our team is available 24/7 for operational support.</Text>
                  </div>
                </div>
                <Button size="sm" variant="primary" label="Contact support" />
              </div>
            </Card>
          </div>
        </div>

        {/* Content */}
        <div style={{ gridColumn: 'span 9' }} className="col-span-9">
          {tab === 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
              {/* Org banner */}
              <Card style={{ padding: '0', overflow: 'hidden' }}>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'row',
                    gap: '20px',
                    alignItems: 'center',
                    padding: '24px',
                    background: 'linear-gradient(90deg, rgba(192, 18, 39, 0.05) 0%, #ffffff 75%)',
                    flexWrap: 'wrap'
                  }}
                >
                  <div style={{ width: '64px', height: '64px', borderRadius: '8px', backgroundColor: '#C01227', color: '#ffffff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Building size={32} />
                  </div>
                  <div style={{ flexGrow: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
                      <Heading level={4}>{general.orgName}</Heading>
                      <Badge variant="success" icon={<CheckCircle2 size={12} />} label="Verified" />
                    </div>
                    <Text type="supporting" color="secondary">{general.supportEmail} · {general.contact}</Text>
                  </div>
                  <Button variant="secondary" size="sm" label="Change logo" />
                </div>
              </Card>

              <Section icon={Sliders} title="Organisation" subtitle="Profile and regional preferences">
                <Row label="Organisation name" description="Shown on invoices and exports">
                  <TextInput label="Organisation name" isLabelHidden width="100%" value={general.orgName} onChange={setG('orgName')} />
                </Row>
                <Row label="Support email" description="Where customer replies are routed">
                  <TextInput label="Support email" isLabelHidden width="100%" type="email" value={general.supportEmail} onChange={setG('supportEmail')} />
                </Row>
                <Row label="Contact number" description="Primary operations line">
                  <TextInput label="Contact number" isLabelHidden width="100%" value={general.contact} onChange={setG('contact')} />
                </Row>
                <Row label="Timezone" description="Used for schedules and reports">
                  <div style={{ width: '100%' }}>
                    <Selector label="Timezone" isLabelHidden options={TIMEZONES} value={general.timezone} onChange={(v) => setG('timezone')(v || '')} />
                  </div>
                </Row>
                <Row label="Language" description="Console display language">
                  <div style={{ width: '100%' }}>
                    <Selector label="Language" isLabelHidden options={LANGUAGES} value={general.language} onChange={(v) => setG('language')(v || '')} />
                  </div>
                </Row>
              </Section>
            </div>
          )}

          {tab === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
              <Section icon={Bell} title="Notification Preferences" subtitle="Choose what you get alerted about">
                {NOTIFY_ROWS.map((row) => (
                  <Row key={row.k} label={row.t} description={row.d} controlAlign="end">
                    <Switch label={row.t} isLabelHidden value={notify[row.k]} onChange={setN(row.k)} />
                  </Row>
                ))}
              </Section>
              <Section icon={Megaphone} title="Delivery Channels" subtitle="How alerts reach your team">
                <Row label="Email alerts" description="Send notifications to the support inbox" controlAlign="end">
                  <Switch label="Email alerts" isLabelHidden value={notify.emailAlerts} onChange={setN('emailAlerts')} />
                </Row>
                <Row label="SMS alerts" description="Send notifications to the registered mobile" controlAlign="end">
                  <Switch label="SMS alerts" isLabelHidden value={notify.smsAlerts} onChange={setN('smsAlerts')} />
                </Row>
              </Section>
            </div>
          )}

          {tab === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
              <Section icon={Lock} title="Change Password" subtitle="Use 8+ characters with a mix of letters, numbers & symbols">
                <Row label="Current password" description="Enter your existing password">
                  <PasswordField label="Current password" value={security.currentPassword} onChange={setSText('currentPassword')} />
                </Row>
                <Row label="New password" description="Choose a strong, unique password">
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', width: '100%' }}>
                    <PasswordField label="New password" value={security.newPassword} onChange={setSText('newPassword')} />
                    {security.newPassword && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginTop: '4px' }}>
                        <div style={{ flexGrow: 1, height: '6px', borderRadius: '3px', backgroundColor: '#f1f5f9', overflow: 'hidden' }}>
                          <div style={{ height: '100%', backgroundColor: pwMeta.color, width: `${(pwScore / 4) * 100}%` }} />
                        </div>
                        <span style={{ fontSize: '0.75rem', fontWeight: 700, color: pwMeta.color, minWidth: '56px' }}>{pwMeta.label}</span>
                      </div>
                    )}
                  </div>
                </Row>
                <Row label="Confirm new password" description="Re-enter the new password">
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', width: '100%' }}>
                    <PasswordField label="Confirm new password" value={security.confirmPassword} onChange={setSText('confirmPassword')} />
                    {mismatch && <span style={{ fontSize: '0.75rem', color: '#ef4444', display: 'block', marginTop: '4px' }}>Passwords do not match</span>}
                  </div>
                </Row>
              </Section>

              <Section icon={Shield} title="Two-Factor Authentication" subtitle="Add an extra layer of security to your account">
                <Row label="Authenticator app" description="Require a one-time code at sign-in for extra security" controlAlign="end">
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <Badge variant={security.twoFactor ? 'success' : 'neutral'} label={security.twoFactor ? 'Enabled' : 'Disabled'} />
                    <Switch
                      label="Two-factor authentication"
                      isLabelHidden
                      value={security.twoFactor}
                      onChange={(v) => { setSecurity((p) => ({ ...p, twoFactor: v })); setDirty(true); }}
                    />
                  </div>
                </Row>
              </Section>

              <Section icon={AlertTriangle} title="Danger Zone" subtitle="Irreversible and high-impact actions" danger>
                <Row label="Sign out of all sessions" description="End every active session on all devices" controlAlign="end">
                  <Button variant="destructive" onClick={() => { localStorage.removeItem('auth_token'); window.location.href = '/login'; }} label="Sign out everywhere" icon={<LogOut size={14} />} />
                </Row>
              </Section>
            </div>
          )}
        </div>
      </div>

      {toast && (
        <div style={{ position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)', backgroundColor: '#0f172a', color: '#ffffff', padding: '12px 24px', borderRadius: '8px', boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)', zIndex: 3000, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.875rem' }}>
          <CheckCircle2 size={16} style={{ color: '#10b981' }} />
          Settings saved successfully.
        </div>
      )}

      <style>{`
        @media (min-width: 1024px) {
          .responsive-row {
            grid-template-columns: repeat(12, 1fr) !important;
          }
          .col-span-3 {
            grid-column: span 3 !important;
          }
          .col-span-9 {
            grid-column: span 9 !important;
          }
        }
        @media (max-width: 1023px) {
          .responsive-row {
            grid-template-columns: 1fr !important;
          }
          .col-span-3, .col-span-9 {
            grid-column: span 1 !important;
          }
        }
        .settings-row:last-child {
          border-bottom: none !important;
        }
      `}</style>
    </div>
  );
}
