'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Pencil, Trash2 } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { appReleasesApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

const EMPTY_FORM = { os: 'android', version: '', forceUpdate: false, storeLink: '', notes: '' };

export default function AppReleasesPage() {
  const queryClient = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({ ...EMPTY_FORM });
  const [formError, setFormError] = useState('');
  const [deleteTarget, setDeleteTarget] = useState<any>(null);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState('');

  const { data, isLoading } = useQuery({
    queryKey: ['app-releases'],
    queryFn: () => appReleasesApi.getAll(),
  });

  const flash = (msg: string) => { setSuccessMessage(msg); setTimeout(() => setSuccessMessage(''), 3000); };

  const saveMutation = useMutation({
    mutationFn: (payload: any) =>
      editing ? appReleasesApi.update(editing.id, payload) : appReleasesApi.create(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['app-releases'] });
      setFormOpen(false);
      setEditing(null);
      setForm({ ...EMPTY_FORM });
      setFormError('');
      flash(editing ? 'Release updated.' : 'Release created.');
    },
    onError: (e: any) => setFormError(e?.response?.data?.message || e?.message || 'Failed to save.'),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => appReleasesApi.remove(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['app-releases'] });
      setDeleteTarget(null);
      setDeleteError(null);
      flash('Release deleted.');
    },
    onError: (e: any) => setDeleteError(e?.response?.data?.message || e?.message || 'Failed to delete.'),
  });

  const openCreate = () => { setEditing(null); setForm({ ...EMPTY_FORM }); setFormError(''); setFormOpen(true); };
  const openEdit = (r: any) => {
    setEditing(r);
    setForm({ os: r.os, version: r.version, forceUpdate: r.forceUpdate, storeLink: r.storeLink || '', notes: r.notes || '' });
    setFormError('');
    setFormOpen(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.version.trim()) { setFormError('Version is required.'); return; }
    saveMutation.mutate({ ...form, version: form.version.trim(), storeLink: form.storeLink || undefined, notes: form.notes || undefined });
  };

  const releases: any[] = Array.isArray(data) ? data : [];

  const columns = [
    {
      key: 'os', label: 'OS',
      render: (r: any) => (
        <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold ${r.os === 'ios' ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300' : 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300'}`}>
          {r.os === 'ios' ? '🍎 iOS' : '🤖 Android'}
        </span>
      ),
    },
    { key: 'version', label: 'Version', render: (r: any) => <span className="font-mono font-semibold">{r.version}</span> },
    {
      key: 'forceUpdate', label: 'Force Update',
      render: (r: any) => <Badge variant="status" status={r.forceUpdate ? 'ACTIVE' : 'INACTIVE'}>{r.forceUpdate ? 'Yes' : 'No'}</Badge>,
    },
    {
      key: 'storeLink', label: 'Store Link',
      render: (r: any) => r.storeLink
        ? <a href={r.storeLink} target="_blank" rel="noreferrer" className="text-primary text-sm underline truncate max-w-[180px] block">{r.storeLink}</a>
        : <span className="text-muted-foreground">—</span>,
    },
    { key: 'notes', label: 'Notes', render: (r: any) => <span className="text-sm text-muted-foreground truncate max-w-[200px] block">{r.notes || '—'}</span> },
    { key: 'createdAt', label: 'Created', render: (r: any) => <span className="text-sm">{formatDateTime(r.createdAt)}</span> },
  ];

  const actions = [
    { label: 'Edit', onClick: openEdit, variant: 'secondary' as const, icon: Pencil },
    { label: 'Delete', onClick: (r: any) => { setDeleteError(null); setDeleteTarget(r); }, variant: 'danger' as const, icon: Trash2 },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">App Releases</h1>
          <p className="text-muted-foreground">Manage mobile app version release control</p>
        </div>
        <ActionButton icon={Plus} onClick={openCreate}>New Release</ActionButton>
      </div>

      {successMessage && (
        <div className="rounded-lg bg-green-50 dark:bg-green-900/20 p-4 text-sm text-green-800 dark:text-green-200">✓ {successMessage}</div>
      )}

      <div className="card">
        <DataTable data={releases} columns={columns} actions={actions} loading={isLoading} emptyMessage="No releases found" />
      </div>

      {/* Create / Edit Modal */}
      <Modal isOpen={formOpen} onClose={() => setFormOpen(false)} title={editing ? 'Edit Release' : 'New Release'} size="md">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">OS</label>
              <select className="input" value={form.os} onChange={(e) => setForm({ ...form, os: e.target.value })}>
                <option value="android">Android</option>
                <option value="ios">iOS</option>
              </select>
            </div>
            <div>
              <label className="label">Version Number</label>
              <input type="text" className="input" placeholder="e.g. 1.2.3" value={form.version}
                onChange={(e) => setForm({ ...form, version: e.target.value })} />
            </div>
          </div>

          <div>
            <label className="label">Force Update</label>
            <div className="flex items-center gap-3 mt-1">
              {(['true', 'false'] as const).map((val) => (
                <label key={val} className="flex items-center gap-2 cursor-pointer">
                  <input type="radio" name="forceUpdate" checked={form.forceUpdate === (val === 'true')}
                    onChange={() => setForm({ ...form, forceUpdate: val === 'true' })} className="w-4 h-4" />
                  <span className="text-sm font-medium">{val === 'true' ? 'Yes — force update' : 'No — optional'}</span>
                </label>
              ))}
            </div>
          </div>

          <div>
            <label className="label">Store Link</label>
            <input type="url" className="input" placeholder="https://play.google.com/..." value={form.storeLink}
              onChange={(e) => setForm({ ...form, storeLink: e.target.value })} />
          </div>

          <div>
            <label className="label">Notes</label>
            <textarea className="input min-h-[80px] resize-y" placeholder="Release notes or changelog..." value={form.notes}
              onChange={(e) => setForm({ ...form, notes: e.target.value })} />
          </div>

          {formError && <p className="text-sm text-red-600 dark:text-red-400">{formError}</p>}

          <div className="flex justify-end gap-2 pt-2 border-t border-muted">
            <ActionButton variant="secondary" onClick={() => setFormOpen(false)}>Cancel</ActionButton>
            <ActionButton type="submit" loading={saveMutation.isPending}>
              {editing ? 'Save Changes' : 'Create Release'}
            </ActionButton>
          </div>
        </form>
      </Modal>

      <ConfirmDialog
        isOpen={!!deleteTarget}
        onClose={() => { setDeleteTarget(null); setDeleteError(null); }}
        onConfirm={async () => { if (deleteTarget) await deleteMutation.mutateAsync(deleteTarget.id); }}
        title="Delete Release"
        message={`Delete ${deleteTarget?.os} v${deleteTarget?.version}? This cannot be undone.`}
        confirmText="Delete" cancelText="Cancel" isLoading={deleteMutation.isPending} isDanger
        error={deleteError ?? undefined}
      />
    </div>
  );
}
